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?
source share