Java 迭代:Hashtable 与 HashMap
当我为哈希表和哈希图运行等效代码时,为什么会得到不同的结果?
Iterator<Integer> it = ht.keySet().iterator();
while(it.hasNext()) {
i = it.next();
System.out.println(i + " : " + ht.get(i));
}
ht 是一个哈希表对象。如果我替换为 hm(一个 hashmap 对象),它不会打印 get() 方法中的值,而是打印 null。这是为什么?
Why do I get different results when I run equivalent code for hashtable and hashmaps?
Iterator<Integer> it = ht.keySet().iterator();
while(it.hasNext()) {
i = it.next();
System.out.println(i + " : " + ht.get(i));
}
ht is a hashtable object. If i replace with hm, a hashmap object, it doesn't print the values from get() method instead prints null. Why is that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
虽然从技术上讲这不是您问题的“答案”(由于问题中提供的代码不足而不可能),但我确实有关于代码样式的建议。
这将帮助您避免在代码中发现的错误(根据您后来的评论)。
您提供的代码:
相当于这个更优雅的 foreach< /a> 循环 条目设置:
使用这个如果可以的话,形式优先于直接使用迭代器。
它更整洁,
代码更少==好
While not technically an "answer" to your question (which is not possible due to insufficient code provided in the question), I do have this suggestion regarding code style.
This would have helped you avoid the bug you found in your code (according to your later comment).
The code you provided:
is equivalent to this more elegant foreach loop over the entry set:
Use this form in preference to using the iterator directly if you can.
It's neater, and
less code == good
我认为使用 HashMap 你必须获取entrySet。然后,您可以循环遍历每个 Entry...
这是有关迭代 HashMap 的参考:
http://www.java2s.com/Code/JavaAPI/java.util/HashMapentrySet.htm
我同意你最初的想法 - 不知道为什么它会这样工作......
I think with a HashMap you have to get the entrySet. Then, you can loop over each Entry...
Here's a ref on iterating a HashMap:
http://www.java2s.com/Code/JavaAPI/java.util/HashMapentrySet.htm
I agree with your initial train of thought though - not sure why it works this way...