LinkedHashMap排序 [英] LinkedHashMap ordering

查看:294
本文介绍了LinkedHashMap排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如javadoc中为LinkedHashMap指定的那样,如果将密钥重新插入到映射中,则插入顺序不会受到影响,但是在运行以下程序时,我注意到在更改访问顺序时再次插入相同的密钥.

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);
    }

在运行上面的程序时,我得到的o/p如下:

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

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

当我重新插入使用的键2时,访问顺序为何会更改.

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

请帮助我了解o/p.

谢谢

推荐答案

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

使用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).

您的getput调用均构成访问".

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

提供了一个特殊的构造函数来创建链接的哈希映射,其迭代顺序是其条目的最后访问顺序(从最近的访问到最近的访问)(访问顺序).这种映射非常适合构建LRU缓存.调用put或get方法将导致对相应条目的访问(假设调用完成后该条目存在).

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).

这篇关于LinkedHashMap排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆