简体   繁体   English

具有并发效果的ConcurrentHashMap

[英]ConcurrentHashMap with add effect

I just tried to get add effect with ConcurrentHashMap<String,String> but the elements order is mixed. 我只是想用ConcurrentHashMap<String,String>来获得添加效果,但是元素顺序混合了。 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? 如果键是一些随机字符串,ConcurrentHashMap是否有办法获取原始元素顺序?

Thanks 谢谢

Use LinkedHashMap instead it will preserve the order of insertion 使用LinkedHashMap代替,它将保留插入顺序

Hash table and linked list implementation of the Map interface, with predictable iteration order. Map接口的哈希表和链表实现,具有可预测的迭代顺序。

And use 并使用

Collections.synchronizedMap(mapInstance)

See Collections.synchronizedMap(mapINstance); 参见Collections.synchronizedMap(mapINstance);

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

LinkedHashMap maintains the order of insertion. LinkedHashMap保持插入顺序。

Hash table and linked list implementation of the Map interface, with predictable iteration order. Map接口的哈希表和链表实现,具有可预测的迭代顺序。 This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. 此实现与HashMap的不同之处在于,它维护贯穿其所有条目的双向链接列表。 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. 请注意,如果将密钥重新插入到映射中,则插入顺序不会受到影响。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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