gpt4 book ai didi

java - 遍历哈希键集时为空值

转载 作者:行者123 更新时间:2023-11-30 09:47:57 25 4
gpt4 key购买 nike

令我困惑的是,尽管在实际哈希表中的相应键上它不是空值,但以下段如何导致强制 boolean 值的空值:

for (List<List<A>> a : hashMap.keySet()) {  
Boolean mandatory = hashMap.get(a);
}

最佳答案

HashMap 将返回null if the key specified is not bound to a value .

问题几乎可以肯定是 a 上的比较操作——一个列表——针对键失败。

让我猜猜:您是否在调用看跌期权后修改这些列表(关键对象)?您是否删除了其中一个键中的所有条目?请记住,空列表等于 所有空的 ArrayList。进一步记住 List.equals() 比较列表内容(一个接一个)来测试相等性。

package sof_6462281;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* Demonstrate the fact that the Map uses key.equals(k) to
* test for key equality. Further demonstrate that it is a
* very bad idea to use mutable collections are keys to maps.
*/
public class ListAsKey {
public static void main(String[] args) {
Map<List<A>, Boolean> map = new HashMap<List<A>, Boolean>();

List<A> alist = new ArrayList<A>();
map.put(alist, true);
for (List<A> a : map.keySet()) {
Boolean b = map.get(a);
System.out.format("\t%s(ArrayList@%d) => %s\n",a, a.hashCode(), map.get(a));
}

// you changed your list after the put, didn't you?
alist.add(new A());
for (List<A> a : map.keySet()) {
Boolean b = map.get(a);
System.out.format("\t%s(ArrayList@%d) => %s\n",a, a.hashCode(), map.get(a));
}

alist.clear();
for (List<A> a : map.keySet()) {
Boolean b = map.get(a);
System.out.format("\t%s(ArrayList@%d) => %s\n",a, a.hashCode(), map.get(a));
}
}
public static final class A { /* foo */ }
}

结果:

[](ArrayList@1) => true
[sof_6462281.ListAsKey$A@4b71bbc9](ArrayList@1265744872) => null
[](ArrayList@1) => true

编辑:在上面添加了更多操作并添加了控制台输出。

关于java - 遍历哈希键集时为空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6462281/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com