Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What order are elements inserted with LinkedHashMap.putAll() in?

I am reading Javadoc for LinkedHashMap, where it is mentioned:

The putAll method generates one entry access for each mapping in the specified map, in the order that key-value mappings are provided by the specified map's entry set iterator.

My question is, what does it mean "one entry access for each mapping". It would be appreciated if anyone could help to provide an example to clarify this.

like image 642
Lin Ma Avatar asked Jan 28 '13 16:01

Lin Ma


1 Answers

This paragraph applies to maps created with the special constructor that makes the iteration order based on last access order (vs. insertion order for a standard LinkedHashMap.

It simply says that if a key K is in the map and you call putAll(someOtherMap) where someOtherMap contains K too, this will be considered as an access to K and it will be moved to the end of the map (from an iteration order's perspective).

In other words, from an access perspective, putAll is equivalent to for (Entry e : entries) map.put(e); (in pseudo code).

Contrived example:

public static void main(String[] args) throws Exception {
    Map<String, String> m = new LinkedHashMap<> (16, 0.75f, true);

    m.put("a", "a");
    m.put("b", "b");
    System.out.println("m = " + m); // a, b
    m.put("a", "a");
    System.out.println("m = " + m); // b, a

    Map<String, String> m2 = new LinkedHashMap<>();
    m2.put("b", "b");

    m.putAll(m2);
    System.out.println("m = " + m); // a, b: putAll was considered as an access
                                    // and the order has changed
}
like image 124
assylias Avatar answered Oct 19 '22 16:10

assylias