简体   繁体   中英

ConcurrentHashMap with add effect

I just tried to get add effect with ConcurrentHashMap<String,String> but the elements order is mixed. Code like a...

ConcurrentHashMap<String,String>h=new ConcurrentHashMap<String,String>();

        for(int i=0; i<10; i++)
        {           
            h.put(""+Math.random(), ""+i);

        }

        Iterator<String> iterator=h.values().iterator();
        while(iterator.hasNext())
        {
            System.out.println(iterator.next());
        }

... gives in console next values:

9
4
6
2
0
5
1
7
3
8

... so my question is...

is there a way for ConcurrentHashMap to get original elements order if key is some random string?

Thanks

Use LinkedHashMap instead it will preserve the order of insertion

Hash table and linked list implementation of the Map interface, with predictable iteration order.

And use

Collections.synchronizedMap(mapInstance)

See Collections.synchronizedMap(mapINstance);

 Map<K,V> map = Collections.synchronizedMap(new LinkedHashMap());

LinkedHashMap maintains the order of insertion.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM