I have a small question about Java Hashmap
. If I override the hashCode
method such that:
@Override
public int hashCode(){
return
Whether it appears as a linked list or not is debatable as it does not state in the documentation. However, it will certainly keep all items with unique keys (i.e. keys that return true
to the equals
method).
class Nine {
final String value;
public Nine(String value) {
this.value = value;
}
@Override
public int hashCode() {
return 9;
}
@Override
public boolean equals(Object it) {
return it instanceof Nine && ((Nine) it).value.equals(value);
}
@Override
public String toString() {
return value;
}
}
class AlwaysNine extends Nine {
public AlwaysNine(String value) {
super(value);
}
@Override
public boolean equals(Object it) {
return it instanceof Nine;
}
}
public void test() {
System.out.println("Hello");
Map testMap = new HashMap();
testMap.put(new Nine("Nine"), "Nine");
testMap.put(new Nine("nine"), "nine");
testMap.put(new AlwaysNine("nIne"), "nIne");
System.out.println(testMap);
}
prints
{Nine=nIne, nine=nine}
which proves that only overriding equals
will force keys to seem to be the same ... as expected because hashCode
is only used to pick the bucket in which to place the object.