I am using this code to check that array is present in the HashMap:
public class Test {
public static void main(String[] arg) {
HashMap<int[], String> map = new HashMap<int[], String>();
map.put(new int[]{1, 2}, "sun");
System.out.println(map.containsKey((new int[]{1, 2})));
}
}
But this prints False. How can I check that array is present in the HashMap?
The problem is because the two
int[]aren’t equal.Mapand other Java Collections Framework classes defines its interface in terms ofequals. FromMap API:Note that they don’t have to be the same object; they just have to be
equals. Arrays in Java extends fromObject, whose default implementation ofequalsreturns true only on object identity; hence why it printsfalsein above snippet.You can solve your problem in one of many ways:
equalsusesjava.util.Arraysequals/deepEqualsmethod.@Override equals(Object), you must also@Override hashCodeList<Integer>that does defineequalsin terms of the values they containequals, you can just stick with what you have. Just as you shouldn’t expect the above snippet to ever printtrue, you shouldn’t ever expect to be able to find your arrays by its values alone; you must hang-on to and use the original references every time.See also:
API
Object.equalsandObject.hashCode