What will be the output of the following code?

import java.util.*;
public class My11 {
    public static void main(String...args) {
        final int num = 3;
        LinkedHashMap<String,String> map = new LinkedHashMap<String,String>(num,1,true) {
            public boolean removeEldestEntry (Map.Entry<String,String> eldest) {
                return size()>num;
            }
        };
        map.put("1", "str1");
        map.put("2", "str2");
        map.put("3", "str3");
        map.put("4", "str4");
        map.get("2");
        System.out.println(map);
    }
}
Explanation
In the LinkedHashMap class constructor the first parameter is a maximum number of elements, usually it doubles with achieving to maximum, but only if method removeEldestEntry returns false (by default it always does it). But in this example it is overriden in an anonymous class and returns true if size()>num.

But the third parameter determines the order in which pairs will be stored < Key, Value >. By default (false), they are stored in the insert-order. If the third parameter is true, access-order is used.

All this can be used to organize an LRU-cache, i.e. adding a new element will remove from the cache element with the longest absence of usage (Least Recently Used - LRU).

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback
Keep exploring
Java quizzes
Cosmo
Sign Up Now
or Subscribe for future quizzes