I have a TreeMap where RobotKey is a class consisting of a string field domain, and a long field timestamp. RobotKey implements comparable as follows:
@Override
public boolean equals(Object obj) {
if (this.domain.equals(((RobotKey) obj).getDomain()))
return true;
return false;
}
And the treemap is sort according to the following compareTo function:
@Override
public int compareTo(RobotKey arg0) {
if (this.lastAccessed < arg0.lastAccessed)
return -1;
else if (this.domain.equals(arg0.getDomain()))
return 0;
else
return 1;
}
So basically, the map is accessed by the domain name and is sorting according to the timestamp.
I did treemap.get(RobotKey e) where e has the same domain name as an existing entry in treemap but a different timestamp. This should return me the correct RobotValue since the Map operations are done with equals. But it instead returns me null indicating the RobotKey is not found. Any idea why this is happening? What am I doing wrong and how do I fix it? Thanks!
The problem is about inconsistency of your equals and compareTo methods.
The
compareTomust return 0 if and only ifequalsreturns true, as far as I remember TreeMap (or TreeSet) does not invoke theequalsmethod, it just usescompareToand its result to indicate duplicate keys.