问题描述
我试图用 keySet()
方法循环 HashMap
,如下:
I am trying to loop over a HashMap
with the keySet()
method as below:
for (String key : bundle.keySet()) {
String value = bundle.get(key);
...
}
我使用很多for-each循环我的代码的其他部分的HashMaps,但这一个作为一个奇怪的行为:它的大小是7(正常),但 keySet
, entrySet
和
值
都是 null
(根据Eclipse调试器)!
I use a lot of for-each loops on HashMaps in other parts of my code, but this one as a weird behavior: its size is 7 (what's normal) but keySet
, entrySet
and values
are null
(according to the Eclipse debugger)!
bundle变量被实例化并填充如下(没有什么是原始的...):
The "bundle" variable is instantiated and populated as follows (nothing original...):
Map <String, String> privVar;
Constructor(){
privVar = new HashMap<String, String>();
}
public void add(String key, String value) {
this.privVar.put(key, value);
}
推荐答案
code> keySet , entrySet
和值
?如果你的意思是 HashMap
的内部字段,那么你不应该看它们,不需要关心它们。它们用于缓存。
What do you mean by keySet
, entrySet
and values
? If you mean the internal fields of HashMap
, then you should not look at them and need not care about them. They are used for caching.
例如,在我使用 keySet()
的Java 6 VM中这个:
For example in the Java 6 VM that I use keySet()
is implemented like this:
public Set<K> keySet() {
Set<K> ks = keySet;
return (ks != null ? ks : (keySet = new KeySet()));
}
因此, keySet
是 null
是不相关的。 keySet()
(方法)将不会返回 null
。
So the fact that keySet
is null
is irrelevant. keySet()
(the method) will never return null
.
entrySet()
和 values()
也是如此。
这篇关于HashMap中的keySet字段为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!