Reputation:
While solving a problem on hackerrank, I found that my output differed from the correct answer because of a logical mistake. I have recreated the logical mistake to explain the situation in a better way.
HashMap<Integer[] , Integer> hm = new HashMap<>();
//both a and b have different hashcode
Integer[] a = {1, 1, 0, 0};
Integer[] b = {1, 1, 0, 0};
hm.put(a,1);
if (!hm.containsKey(b)) {
//key does not exists so, create new one
hm.put(b, 1);
}
else {
//key does exists so, put its value = value + 1
hm.put(b, hm.get(b)+1);
}
Here hm.containsKey(b) return false but if it returns true my output will match to the correct one. How do I make containsKey(b) return true since content of a and b are equal?
Upvotes: 0
Views: 175
Reputation: 393936
You shouldn't use an array as the key of a HashMap
, since arrays don't override equals
and hashCode
, so different array instances that contain the exact same elements are not considered identical by the HashMap
.
Use List<Integer>
keys instead.
Map<List<Integer>, Integer> hm = new HashMap<>();
List<Integer> a = List.of(1, 1, 0, 0);
List<Integer> b = List.of(1, 1, 0, 0);
hm.put(a,1);
if (!hm.containsKey(b)) {
//key does not exists so, create new one
hm.put(b, 1);
}
else {
//key does exists so, put its value = value + 1
hm.put(b, hm.get(b)+1);
}
Upvotes: 4