Java map.containsKey not working

This may seem like a simple question, but I tried a couple of hours (without having to implement a hashCode comparison) so that make containsKey worked. To simplify things, I will post a simple code example that I'm having problems with:

public class myPair { private int a; private int b; myPair(int x, int y) { a=x; b=y; } public boolean equals(Object pair) { System.out.println("Ola"); return true; } int first() { return a; } int second() { return b; } public String toString() { return "X: "+this.a + " Y:"+this.b; } } public class Main { public static void main(String args[]){ Map<myPair,String> myMap = new LinkedHashMap<myPair, String>(); myMap.put(new myPair(2, 2), "encontrou me"); if(myMap.containsKey(new myPair(2, 2))){ System.out.println(myMap.get(new myPair(2, 2))); } System.out.println(myMap.get(new myPair(2,2))); } } 

It is output:

 null 

I applied the equals method ... why doesn't it work?

+4
source share
4 answers

Because you have to override hashCode in order to use HashMap (or LinkedHashMap ). Here's how the hash maps work: they first compute the hash code to get a rough idea of ​​where to look for the object. If the hash code does not match the hash code of the targets, it just looks for the object in the wrong place!

This is from the Object.hashCode API Object.hashCode :

  • If two objects are equal in accordance with the equals (Object) method, then calling the hashCode method for each of the two objects should give the same integer result.

The default hashCode by default will not return the same hash code for two different objects.

Basically, you break the API contract by overriding equals but not hashCode .

+11
source

You also need to override the hashCode method as described by aioobe and hvgotcodes .
Since equals always returns true , the hashCode method must always return the same value:

  @Override public int hashCode() { return 123; // qualquer nΓΊmero (any other number) } 

but I doubt that an object with the equals method, always returning true , is very useful. At least, this is not a key for the card: it is not possible to have more than one key-value pair in the card, since there are no separate keys. (possibly useful for testing)

+1
source

you need a hashCode method, and your equals method always returns true, which is wrong.

0
source

You can learn these concepts from the excellent book by Khalid Mogul and Rolf U Rasmussen. It is called SCJP.

-3
source

All Articles