J'ai un Map<Integer,Double>
comme champ. J'ai besoin d'implémenter equals()
pour cette classe donnée. Comment comparer les doubles valeurs en utilisant une tolérance.Comparer une carte des doubles
0
A
Répondre
1
public class Foo {
Map<Integer, Double> data;
public Map<Integer, Double> getData() {
return data;
}
public void setData(Map<Integer, Double> data) {
this.data = data;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof Foo))
return false;
Foo foo = (Foo) o;
if (this.data.size() != foo.getData().size())
return false;
Set<Integer> keySet1 = data.keySet();
Set<Integer> keySet2 = foo.getData().keySet();
// keys should same
if (keySet1.containsAll(keySet2) && keySet2.containsAll(keySet1)) {
// for the same key, the values are close
for (Integer key : keySet1) {
if (!isEntryEqual(data.get(key), foo.getData().get(key))) {
return false;
}
}
return true;
}
return false;
}
// also need to override the hashCode method
@Override
public int hashCode() {
List<Integer> keys = new ArrayList<Integer>(this.data.keySet());
return Objects.hash(keys);
}
public static final Double PRECISION = 0.0001;
private static boolean isEntryEqual(Double d1, Double d2) {
return d1 - d2 < PRECISION;
}
}
+0
Une implémentation correspondante de 'hashCode()' est manquante. – Axel
+0
Grand fonctionne comme un charme. – LonsomeHell
+0
Je pense que hashCode() peut être raccourci à 'return this.data.keySet(). HashCode()'. – Axel
vous pouvez toujours faire la différence entre les deux et vérifier si elle est plus grande que la tolérance –
Que comparez-vous? Les clés? Les valeurs? Chaque entrée? – Nathan
Vous * n'implémentez pas equals() 'avec une tolérance. Utilisez un autre nom de méthode. Sinon, vous rencontrerez des problèmes - en commençant par casser le [contrat entre 'hashCode()' et 'equals()'] (https://stackoverflow.com/questions/27581/what-issues-should-be-considered-when -overriding-equals-et-hashcode-in-java). – Axel