Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep the order of elements in hashtable

Tags:

I have a hashtable . values() method returns values in some order different from the order in which i am inserted.How can i get the values in the same order as i inserted?Using LinkedHashmap is an alternative but it is not synchronized.

like image 550
Thomas Manalil Avatar asked Sep 14 '09 04:09

Thomas Manalil


People also ask

Does Hashtable maintain order?

Hashtable is a data structure that stores data in key-value format. The stored data is neither in sorted order nor preserves the insertion order.

Why is Hashtable not ordered?

HashTable implements a dictionary, and total order of insertions is not retained because insertions with different hash values map to different chains.

How are elements stored in hash table?

To store an element in the hash table you must insert it into a specific linked list. If there is any collision (i.e. two different elements have same hash value) then store both the elements in the same linked list. The cost of a lookup is that of scanning the entries of the selected linked list for the required key.

Does HashMap maintain insertion order?

HashMap does not maintains insertion order in java. Hashtable does not maintains insertion order in java. LinkedHashMap maintains insertion order in java. TreeMap is sorted by natural order of keys in java.


1 Answers

Use a LinkedHashMap.

Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order). Note that insertion order is not affected if a key is re-inserted into the map. (A key k is reinserted into a map m if m.put(k, v) is invoked when m.containsKey(k) would return true immediately prior to the invocation.)

combined with Collections.synchronizedMap().

So, for example:

Map<String, String> map = Collections.synchronizedMap(   new LinkedHashMap<String, String>()); 
like image 131
cletus Avatar answered Sep 30 '22 19:09

cletus