LinkedHashMap ordering

…衆ロ難τιáo~ 提交于 2020-01-04 01:37:09

问题


As specified in the javadoc for LinkedHashMap, insertion order is not affected if a key is re-inserted into the map but While running the below program,I notice that inserting the same key again in changing the access order.

Map<Integer, String> map = new LinkedHashMap<Integer,String>(16, .75f, true);
    map.put(new Integer(1), "Ajay");
    map.put(new Integer(2), "Vijay");
    map.put(new Integer(3), "Kiran");
    map.put(new Integer(4), "Faiz");

    for(String value:map.values()){
        System.out.println(value);
    }

    String val =map.get(new Integer(3));
    map.put(new Integer(2), "Ravi");
    System.out.println("After changes...");
    for(String value:map.values()){
        System.out.println(value);
    }

On Running the above program i am getting the o/p as follows:

Ajay
Vijay
Kiran
Faiz
After changes...
Ajay
Faiz
Kiran
Ravi

when i reinsert the key 2 using, why it's access order is changed.

Please help me to understand the o/p.

Thanks,


回答1:


new LinkedHashMap<Integer,String>(16, .75f, true);

With that true you specify that you want an "access-ordered" map, not an "insertion-ordered" map.

This means that you will get the values in the order of access (least recently accessed first).

Both your get and put calls constitute an "access".

A special constructor is provided to create a linked hash map whose order of iteration is the order in which its entries were last accessed, from least-recently accessed to most-recently (access-order). This kind of map is well-suited to building LRU caches. Invoking the put or get method results in an access to the corresponding entry (assuming it exists after the invocation completes).



来源:https://stackoverflow.com/questions/35838739/linkedhashmap-ordering

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!