Why is insertion order not preserved in MultiMap?

后端 未结 2 907
囚心锁ツ
囚心锁ツ 2021-02-14 16:08
public class MultiMap_Test {
    public static void main(String[] args) {
        Multimap myMultimap = ArrayListMultimap.create();

          myMu         


        
相关标签:
2条回答
  • 2021-02-14 16:30

    Use LinkedListMultimap instead if you want to keep the insertion order:

    Multimap<String, String> myMultimap = LinkedListMultimap.create();
    
    0 讨论(0)
  • 2021-02-14 16:42

    Why is insertion order not preserved in MultiMap?

    In fact, your problem is not with MultiMap but with the selected implementation. ArrayListMultimap uses a HashMap<K, Collection<V>> as implementation of the backing Map<K, Collection<V>>:

    public static <K, V> ArrayListMultimap<K, V> create() {
        return new ArrayListMultimap<K, V>();
    }
    
    //...
    
    private ArrayListMultimap() {
        super(new HashMap<K, Collection<V>>());
        expectedValuesPerKey = DEFAULT_VALUES_PER_KEY;
    }
    

    And HashMap doesn't preserve the order of the insertion of the elements.

    0 讨论(0)
提交回复
热议问题