Perhaps not the best name, please edit it.
This is the code I have.
import java.util.Map;
import java.util.HashMap;
public class App {
public static void main(String[] args) {
final Foo foo = new Foo();
final Foo bar = new Foo();
System.out.println("foo equals foo: " + foo.equals(foo));
System.out.println("foo equals bar: " + foo.equals(bar));
System.out.println("foo hashcode: " + foo.hashCode());
System.out.println("bar hashcode: " + bar.hashCode());
final Map<Foo, Integer> foos = new HashMap<Foo, Integer>();
foos.put(foo, -99);
System.out.println("foos.getfoo: " + foos.get(foo));
System.out.println("foos.getbar: " + foos.get(bar));
}
}
class Foo {
@Override
public boolean equals(Object o) {
return false;
}
@Override
public int hashCode() {
return -1;
}
}
So, before reading further, you can guess what will be displayed for the next operator 2?
System.out.println("foos.getfoo: " + foos.get(foo));
System.out.println("foos.getbar: " + foos.get(bar));
I would expect to see:
null
null
since even if the hash codes really match, Fooit will always return false for any instance , so using the instance Fooas a key on the map should not be useful at all.
However, the conclusion:
:~ $ javac App.java
:~ $ java App
foo equals foo: false
foo equals bar: false
foo hashcode: -1
bar hashcode: -1
foos.getfoo: -99
foos.getbar: null
What am I missing? How is -99 extracted when I use an object with hashcode -1 and is NOT equal to myself, but then get null later with the same type of instance, which is also NOT equal to what I have on the Map, and also has hashcode -1?