3

My Program is public class Demo {

public static void main(String[] args) {
    List<String> arr = new ArrayList<>();
    arr.add("a");
    arr.add("b");
    Map<List<String>, String> map = new HashMap<>();
    map.put(arr, "Ravinda");
    System.out.println(map.get(arr));
    arr.add("c");
    System.out.println(map.get(arr));
}

}

Output is: Ravindra and null

I am not able to get why the output of second System.out.println is null.

Can anyone please explain.

2 Answers2

3

When you call: map.put(arr, "Ravinda"); you are setting the key of the "Ravinda" value to be a List containing two strings.

By calling arr.add("c"); you are modifying List used earlier to index the "Ravinda" value in your hashmap.

Since the arr List has been changed, it no longer matches the key specified when you called: map.put(arr, "Ravinda");

This is why the hashmap is returning a null value when you try to access it for the second time.

The hashmap still contains the 'Ravinda' value, but this value is indexed against the list containing only the two values.

Guybrush
  • 227
  • 3
  • 13
2

As this answer explains, you need to be careful when using an object who's hash code is mutable. The hashCode method for an ArrayList varies depending on the elements it contains, so by adding "c" to the list you have changed its hash code.

It's important to note that even if the hash code did not change, the lists would still have to be equal. An object's hash code is not a unique identifier, so internally HashMap uses an equals comparison on the key after retrieving the bucket it is in.

If you have a program that is in this position, you need to take a step back and determine another solution to the problem at hand. There is no reliable method to use a mutable list in a Map that doesn't boil down into reference equality (which makes things pretty pointless anyway).

Jay Castell
  • 68
  • 1
  • 6