Wenn ich ein Hash-Set für meine Elemente erstelle, kann ich aus irgendeinem Grund doppelte Elemente hinzufügen. Ich habe die equals- und hashcode-Methoden überschrieben. Darunter ist ein bisschen von meinem Code und ein Beispiel für mein Problem. Der Einfachheit halber nannte ich meine Elemente "Element".Warum enthält mein hashset Duplikate?
set.add(new element(new Point2D.Double(0,1), new Point2D.Double(2, 3), true));
set.add(new element(new Point2D.Double(0,1), new Point2D.Double(2, 3), true));
for (element e : set)
System.out.println("set element : " + e.firstPoint2D.toString()
+ e.secondPoint2D.toString()
+ e.lastBoolean
+ " and hashcode = " + e.hashCode());
dies zurück:
set element : Point2D.Double[0.0, 1.0] Point2D.Double[2.0, 3.0] true
and hashcode = 3211
set element : Point2D.Double[0.0, 1.0] Point2D.Double[2.0, 3.0] true
and hashcode = 3211
Wir klar sehen, dass sie den gleichen Hash-Code haben, also warum sind sie beide in der Hashset? Ich dachte, das Dienstprogramm eines Hashsets würde darin bestehen, dass es keine Duplikate enthalten könnte? Fehle ich etwas? Hier ist equals und hashcode:
public boolean equals(element e) {
if (this.firstPoint2D.equals(e.firstPoint2D) &&
this.secondPoint2D.equals(e.secondPoint2D) &&
this.lastBoolean == e.lastBoolean)
return true;
else
return false;
}
@Override
public int hashCode() {
int result = (int)(firstPoint2D.getX() + 10*firstPoint2D.getY()
+ 100*secondPoint2D.getX() + 1000*secondPoint2D.getY());
if (lastBoolean)
return result + 1;
else
return result;
}
Konnten Sie die Methode 'equals' für' Point2D.Double' posten? Ihr Problem ist wahrscheinlich dort - in 'Point2D.hashCode' erzeugen Sie manuell den' hashCode' für 'Point2D.Double', aber in' Point2D.equals' verlassen Sie sich auf 'Point2D.Double.equals' - das ist wahrscheinlich falsch. –
Versuchen Sie, Ihrer equals-Methode '@ Override' hinzuzufügen. Immer. – Pshemo
@BoristheSpider Ich vermute, OP verwendet 'java.awt.geom.Point2D.Double'. – Pshemo