Ari53nN3o
Ari53nN3o

Reputation: 1202

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. If i replace with hm, a hashmap object, it doesn't print the values from get() method instead prints null. Why is that?

Upvotes: 2

Views: 2700

Answers (2)

Bohemian
Bohemian

Reputation: 425198

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:

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

Upvotes: 3

Brian
Brian

Reputation: 2778

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...

Upvotes: 1

Related Questions