Reputation: 3057
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
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
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
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