Reputation: 2404
Hello I cannot find any info on what I need to do to make two keys seems equal. That is, i need to provide a custom compare method that will be used by map.put() Implementing comparable doesnt help.
For example, this code doesnt work as intended - for the purposes of my program, two keys n and n2 ARE the same.
private class N implements Comparable<N> {
int value;
int stuff;
String z;
@Override
public int compareTo(N arg0) {
if (arg0.z.equals(z))
return 0;
return 1;
}
}
public void dostuff() {
HashMap m = new HashMap();
N n = new N();
n.z = "1";
N n2 = new N();
n2.z = "1";
m.put(n, "one");
m.put(n2, "two");
// will print refs to two instances! - wrong
Iterator it = m.keySet().iterator();
while (it.hasNext()) {
System.err.println(it.next());
}
}
Upvotes: 0
Views: 821
Reputation: 1500365
You need to override equals
and hashCode
- HashMap
doesn't use compareTo
, which is meant for sorting.
Note that your compareTo
implementation is already broken, as it's really only testing for equality. In particular, x.compareTo(y)
and y.compareTo(x)
both returning 1 violates the contract of compareTo
:
The implementor must ensure sgn(x.compareTo(y)) == -sgn(y.compareTo(x)) for all x and y.
Upvotes: 4