class Point{
int x, y, l;
Point(int x, int y, int l){
this.x =x;
this.y =y;
this.l=l;
}
@Override
public int hashCode() {
return y;
}
@Override
public boolean equals(final Object obj) {
if(this == obj) return true;
if(!(obj instanceof Point)) return false;
Point p = (Point) obj;
return this.x == p.x && this.y == p.y;
}
}
TreeMap<Point,Integer> sortedMap = new TreeMap<>((p1, p2)-> p1.l-p2.l);
sortedMap.put(new Point(4,5,0),0);
sortedMap.put(new Point(5,5,0),6);
System.out.println(sortedMap.size()); -> Output: 1
System.out.println((new Point(4,5,0)).equals(new Point(5,5,0))); -> Output -> False.
I have overloaded both hashcode, equals method in class. I think put method should use equals method to determine whether the same object exits or not. But it is not working as expected.
I am not sure why my hashMap size is 1. Please let me know if I understood hashmap working wrongly. Help me to identify bug in this code ?
p1.l - p2.l
? – KittrellsortedSet
when it's not a set but a map? – VenetishashCode
implementation for the givenequals
method. Yes, it'll give the same hash code for multiple equal values, but that's fine. (It would potentially cause inefficiencies, but it's valid.) – BuilderTreeMap
- which is correct? – Grecian