简体   繁体   English

可以AnyOne请解释这个HashMap行为

[英]Can AnyOne Please Explain this HashMap Behaviour

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 输出为:Ravindra和null

I am not able to get why the output of second System.out.println is null. 我无法理解为什么第二个System.out.println的输出为空。

Can anyone please explain. 任何人都可以解释。

When you call: map.put(arr, "Ravinda"); 当你打电话: map.put(arr, "Ravinda"); you are setting the key of the "Ravinda" value to be a List containing two strings. 您将“Ravinda”值的键设置为包含两个字符串的List。

By calling arr.add("c"); 通过调用arr.add("c"); you are modifying List used earlier to index the "Ravinda" value in your hashmap. 您正在修改先前使用的List以索引hashmap中的“Ravinda”值。

Since the arr List has been changed, it no longer matches the key specified when you called: map.put(arr, "Ravinda"); 由于arr List已被更改,因此它不再匹配您调用时指定的键: map.put(arr, "Ravinda");

This is why the hashmap is returning a null value when you try to access it for the second time. 这就是当您尝试第二次访问时,hashmap返回空值的原因。

The hashmap still contains the 'Ravinda' value, but this value is indexed against the list containing only the two values. hashmap仍包含'Ravinda'值,但此值是针对仅包含两个值的列表编制索引的。

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. ArrayListhashCode方法因其包含的元素而异,因此通过在列表中添加"c" ,您已更改其哈希码。

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. 对象的哈希码不是唯一标识符,因此内部HashMap在检索其所在的存储桶后对密钥使用equals比较。

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). 没有可靠的方法在Map中使用可变列表,而不是归结为引用相等(这使得事情无论如何都是毫无意义的)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM