When I create a hashset for my elements, for some reason I can add duplicate elements to it. I did override the equals and hashcode methods. Underneath is a bit of my code and an example of my problem. For simplicity I named my elements "element".
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());
this returns :
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
We clearly see they have the same hashcode, so why are they both in the hashset? I thought a hashset's utility was in the fact that it couldn't contain duplicates? Am I missing something? Here is equals and 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;
}