简体   繁体   English

Java迭代:Hashtable与HashMap

[英]Java Iteration: Hashtable vs HashMap

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. ht是一个哈希表对象。 If i replace with hm, a hashmap object, it doesn't print the values from get() method instead prints null. 如果我用一个哈希表对象hm代替,它不会打印get()方法中的值,而是打印null。 Why is that? 这是为什么?

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: 您提供的代码:

Iterator<Integer> it = ht.keySet().iterator();
while(it.hasNext()) {
    i = it.next();
    System.out.println(i + " : " + ht.get(i));
}

is equivalent to this more elegant foreach loop over the entry set : 等效于条目集上这个更优雅的foreach循环:

for (Map.Entry<Integer, Object> entry : ht.entrySet()) {
    System.out.println(entry.getKey() + " : " + entry.getValue());
}

Use this form in preference to using the iterator directly if you can. 如果可以,请优先使用此表单,而不要直接使用迭代器。
It's neater, and less code == good 更整洁, less code == good

I think with a HashMap you have to get the entrySet. 我认为必须使用HashMap才能获得entrySet。 Then, you can loop over each Entry... 然后,您可以遍历每个条目...

Here's a ref on iterating a HashMap: 这是迭代HashMap的参考:

http://www.java2s.com/Code/JavaAPI/java.util/HashMapentrySet.htm 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... 不过,我同意您最初的思路-不知道为什么会这样工作...

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

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