Reputation: 6050
I don't understand something silly in Java and was hoping you could clear it up for me.
I have defined Hashset<Point> myHashSet = new HashSet<Point>();
Then, I create two equal Point points, Point p1 and Point p2
, and put them in different variables/memory locations. Then I override the .equals() method for public boolean equals(Point other)
and added my first point, p1, to the HashSet.
Then I call System.out.println(myHashSet.contains(p2)); // prints false
Why can the compiler not infer "Oh, this hashset is of type Point" from the when it is being created and say "I should check to see if Point has overridden the default equals method...yup, let's call that one!".
Instead, I believe it calls the generic equals method for objects, thus comparing memory location, I believe ?
Is the reasoning for this simply that the HashSet could contain a subclass of Point which uses a different Equals method ? This is the only reason I can see for the current behaviour, though I am sure I am overlooking something :). Thanks a lot.
Upvotes: 1
Views: 139
Reputation: 10553
Try adding @Override
annotation. You must have misspelled equals method and its signature.
@Override
public boolean equals(Object obj) {
// TODO Auto-generated method stub
return super.equals(obj);
}
Upvotes: 1
Reputation: 53
Your problem lies in public boolean equals(Point other)
, because that is NOT the default equals method defined in the Object
class.
You must override public boolean equals(Object other)
(notice Object instead of Point) if you wish the HashMap to use your implementation. See the the documentation for Object and note also that if you override equals
you SHOULD also override the hashCode()
method.
Upvotes: 2
Reputation: 902
You should override both equals() and hashCode() according to this doc http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html#hashCode%28%29, since HashSet use both of these methods to check if objects are equal
Upvotes: 2
Reputation: 533870
Collections use Object.equals(Object)
which you have to override. If you create another method like equals(Point)
it won't call it.
Instead, I believe it calls the generic equals method for objects, thus comparing memory location, I believe ?
Yes, as the only method which HashSet
can generically call is equals(Object)
Is the reasoning for this simply that the HashSet could contain a subclass of Point which uses a different Equals method ?
The HashSet has no way of know that you want to use this method instead at runtime.
Upvotes: 6