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)); 
  • And what integer do you use? Also your something? - LEQADA
  • This is a mistake, there is a normal int, not used to Java yet - Mikhail

1 answer 1

You urgently need to override hashCode() .
Some people say that hashCode() in Object uses random numbers and thus both of your equivalent keys have different hash.
Different hash - different objects. equals() doesn't even get to it.
By the way, here is the article http://habrahabr.ru/post/168195/

  • thanks for the article, figured out - Mikhail
  • You're welcome. And this article, if anything, is not mine :) Thanks to the author. - Sergey