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());
}
}
You need to override
equalsandhashCode–HashMapdoesn’t usecompareTo, which is meant for sorting.Note that your
compareToimplementation is already broken, as it’s really only testing for equality. In particular,x.compareTo(y)andy.compareTo(x)both returning 1 violates the contract ofcompareTo: