How to keep the order of elements in hashtable

前端 未结 5 1163
庸人自扰
庸人自扰 2020-12-06 09:51

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?Us

5条回答
  •  Happy的楠姐
    2020-12-06 10:02

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

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

    From the JavaDoc:

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

提交回复
热议问题