I do not understand why it does not work. We have the code, it has a Map
, as the key we use this type of class
class Key { public int x; public int y; Key(integer x, integer y) { this.x = x; this.y = y; } @Override public boolean equals(Object obj) { if (obj == this) return true; if (obj == null) return false; if (!(this.getClass() == obj.getClass())) return false; else { Key tmp = (Key) obj; return this.x == tmp.x && this.y == tmp.y ? true : false; } }
And we are trying to put the String
value in the Map
and remove it by key.
void funk() { Map < Key, String > map = new HashMap < Key, String > (); map.put(new Key(1, 1), "Hello world"); System.out.println(map.get(new Key(1, 1))); }
But we get null
. In theory, equals
redefined and works correctly, what is wrong?
And why does this work correctly?
Map<String,String> map = new HashMap<String, String>(); String s = "Key"; map.put(s, "Hello world"); String s1 = "Key"; System.out.println(map.get(s1));