2

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?

8
  • Are you sure, that you did not forget to switch the objects at initialization? Specifically, that you put the objects into ht, but try to retrieve them from hm? Commented Jul 27, 2011 at 16:08
  • 2
    The difference must come from some other reason. Try to output simply ht.toString() for comparison. Commented Jul 27, 2011 at 16:10
  • 3
    I don't get different results when I run a more complete test case . (well, I get different orderings). Would you post the full code that you used? Commented Jul 27, 2011 at 16:16
  • Sorry folks, I switched iterator usage at one point which produced bad results. Rectified it, thanks for the comments! Commented Jul 27, 2011 at 16:29
  • @dryHump: Could you post an answer with your "solution"? Commented Jul 27, 2011 at 18:33

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

You can do this, and it's more efficient, but there's no reason keySet() + get() shouldn't work.
@David - thanks for this - I'm new to Java and had issues w/ keySet similar to Dry's... I've been using entrySet ever since... apparently to my benefit, but for the wrong reason :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.