What does Java – HashMap check when calling containskey()?
ArrayList<Integer> lis = new ArrayList<Integer>();
ArrayList<Integer> lis = new ArrayList<Integer>(); lis.add(2); lis.add(3); ArrayList<Integer> lis2 = new ArrayList<Integer>(); lis2.add(2); lis2.add(3); HashMap<ArrayList<Integer>,Integer> map = new HashMap<ArrayList<Integer>,Integer>(); map.put(lis,7); System.out.println(map.containsKey(lis2));
Initially, I want the code to print 'false' because LIS and lis2 are different objects Surprisingly, the code prints "real" What does HashMap check when calling containskey()?
Solution
It checks Hashcode to find the bucket, and then use equals. If the order of all elements is the same and the same Equals, then list Equals returns true ArrayList. Hashcode will return the same value for two ArrayList instances with the same element, so it finds the correct bucket and uses Equals and see if the elements of the list are the same and in the same order
For example:
ArrayList<Integer> lis = new ArrayList<Integer>(); lis.add(2); lis.add(3); ArrayList<Integer> lis2 = new ArrayList<Integer>(); lis2.add(2); lis2.add(3); System.out.println(lis.equals(lis2)); // Prints "true"
It is worth noting that you should never use mutable objects as keys in a HashMap By modifying the key, the bucket in which it is located can be invalidated For example, if I do this:
map.put(lis,7); lis.add(3); System.out.println(map.get(lis)); // Prints "null",*not* "7"
This is because adding another element changes LIS The value of hashcode() When placing the list, hashcode is used to select the bucket By adding a new element, you can change the bucket it will use, but not the bucket of an item that has been added to the map Add to above:
map.put(lis,7); lis.add(3); map.put(lis,7); System.out.println(map.size()); // Prints "2"
It resolves to another bucket the second time, so it treats it as the second element
In this case, you will use collections Unmodifiablelist to "freeze" the list, add it, and then never touch it again:
map.put(Collections.unmodifiableList(lis),7);
Then, if you call get() add(3):
map.get(7).add(3);
This will throw an unsupported operationexception