max
max

Reputation: 3057

hashtable values reordered

I have a hashtable, which contains strings for example, when I use put method as below

 hashtable.put("1","A");
 hashtable.put("1","B");
 hashtable.put("1","C");
 hashtable.put("1","D");
 hashtable.put("1","E");

Then when I try to print it back it doesn't print in same order, Any one knows why would something like this happen?

 Collection c = ht.values();
 Iterator itr = c.iterator();
 while(itr.hasNext())
 System.out.println(itr.next());

Thanks Max

Upvotes: 0

Views: 782

Answers (4)

Jeremy
Jeremy

Reputation: 22415

A Hashtable does not guarantee any kind of ordering.

If you want to preserve insertion order, use a LinkedHashMap. However, the contract is slightly different than a Hashtable in that it allows null elements.

Upvotes: 4

Android Killer
Android Killer

Reputation: 18499

HashTable doesnot keep order.It will print randomly.You should go for LinkedHashMap.You can use LinkedHashMap in the same manner as you did for HashMap.Just put LinkedHashMap in place of HashMap.LinkedHashMap keeps the order of data in which you enter into it.

Upvotes: 1

michel-slm
michel-slm

Reputation: 9756

That is simply the property of a hash table -- it makes no guarantee about ordering. Do you want to use a LinkedHashMap instead?

Upvotes: 2

amit
amit

Reputation: 178461

you should use LinkedHashMap if you want to print items in order.

Upvotes: 3

Related Questions