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.
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.
HashTable implements a dictionary, and total order of insertions is not retained because insertions with different hash values map to different chains.
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.
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.
Use a LinkedHashMap
.
Hash table and linked list implementation of the
Map
interface, with predictable iteration order. This implementation differs fromHashMap
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 ifm.put(k, v)
is invoked whenm.containsKey(k)
would returntrue
immediately prior to the invocation.)
combined with Collections.synchronizedMap()
.
So, for example:
Map<String, String> map = Collections.synchronizedMap( new LinkedHashMap<String, String>());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With