How to keep the order of elements in hashtable

前端 未结 5 1177
庸人自扰
庸人自扰 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条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-06 10:20

    Use a LinkedHashMap.

    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. (A key k is reinserted into a map m if m.put(k, v) is invoked when m.containsKey(k) would return true immediately prior to the invocation.)

    combined with Collections.synchronizedMap().

    So, for example:

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

提交回复
热议问题