[ACCEPTED]-How to keep the order of elements in hashtable-linkedhashmap

Accepted answer
Score: 36

Use a LinkedHashMap.

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

combined 1 with Collections.synchronizedMap().

So, for example:

Map<String, String> map = Collections.synchronizedMap(
  new LinkedHashMap<String, String>());
Score: 4

You could either wrap a LinkedHashMap and synchronize 13 or you could use the Collections.synchronizedMap utility to create 12 a synchronized LinkedHashMap:

Map m = Collections.synchronizedMap(new LinkedHashMap(...));

From the JavaDoc:

If multiple 11 threads access a linked hash map concurrently, and 10 at least one of the threads modifies the 9 map structurally, it must be synchronized 8 externally. This is typically accomplished 7 by synchronizing on some object that naturally 6 encapsulates the map. If no such object 5 exists, the map should be "wrapped" using 4 the Collections.synchronizedMap method. This 3 is best done at creation time, to prevent 2 accidental unsynchronized access to the 1 map

Score: 3

I'm pretty sure that the reason hashtables 5 are unsorted is to aid storage and retrieval 4 speed. Because of this I would suggest using 3 an external structure to maintain ordering 2 and just using the hashtable for storing 1 values (for fast lookup).

Score: 2

A hash table is inherently unordered, so 5 you are using the wrong data structure. Since 4 you don't specify what language you are 3 using I cannot suggest an alternate, but 2 you need some type of ordered key/value 1 set.

Score: 1

If jdk1.6 you have only two type of ordered 4 map EnumMap and LinkedHashMap. Both of them 3 are not synchronized. If you just need to 2 remember the order, use

Map m = Collections.synchronizedMap(new LinkedHashMap(...));

if you want sorted 1 then use ConcurrentSkipListMap

More Related questions