Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LinkedHashMap order issue

It is mentioned in the LinkedHashMap Javadocs:

In particular, operations on collection-views do not affect the order of iteration of the backing map.

What does "operations on collection-views" mean?

like image 765
Lin Ma Avatar asked Jan 31 '13 16:01

Lin Ma


3 Answers

The collection-views of Maps are the objects returned by:

  • Map#keySet()
  • Map#values()
  • Map#entrySet()

Operations on those simply means any method calls on the collection-view instance.

like image 151
Matt Ball Avatar answered Nov 02 '22 23:11

Matt Ball


This test is supposed to demonstrate how it works

    Map m = new LinkedHashMap(16, 0.75f, true);
    m.put(1, 1);
    m.put(2, 2);
    m.put(3, 3);
    System.out.println(m);
    m.get(2);
    System.out.println(m);
    Set keys = m.keySet(); //API: Returns a Set view of the keys contained in this map.
    keys.iterator().next();
    System.out.println(m);

output

{1=1, 2=2, 3=3}
{1=1, 3=3, 2=2}
{1=1, 3=3, 2=2}

that is, accessing entry 2-2 changed the iteration order, and accessing the first entry 1-1 on the keySet view did not

like image 38
Evgeniy Dorofeev Avatar answered Nov 02 '22 22:11

Evgeniy Dorofeev


If I understand well, maybe I don't, the collection-view are the Collections obtained by its abstractions, like entrySet, values and keySet.

Operations in these sets will not affect the order of access of the objects inside yours LinkedHashMap when you're using the special constructor that makes your objects be order by access-order.

like image 39
Caesar Ralf Avatar answered Nov 02 '22 22:11

Caesar Ralf