LinkedHashMap.java使用的一个字段是:

final boolean accessOrder;

LinkedHashMap的构造函数为:
public LinkedHashMap(int initialCapacity,
                         float loadFactor,
                         boolean accessOrder) {
        super(initialCapacity, loadFactor);
        this.accessOrder = accessOrder;
    }

我想知道字段accessOrder的目的。请举例说明accessOrder是“true”还是“false”。还有其他方法可以更新已经创建的对象的accessOrder字段吗?

最佳答案

可以按照将键首次添加到Map的顺序(这是默认行为)或根据访问顺序(即,最近访问的条目将是最后迭代的最后一个条目)对LinkedHashMap的条目进行迭代。

通过将true传递给该构造函数中的accessOrder参数,您就是说希望根据访问顺序(而不是插入顺序)遍历条目。

Map<Integer,String> insertOrder = new LinkedHashMap<>(16,0.75f,false);
Map<Integer,String> accessOrder = new LinkedHashMap<>(16,0.75f,true);

insertOrder.put (1,"a");
insertOrder.put (3,"c");
insertOrder.put (2,"b");
String v = insertOrder.get(3);

accessOrder.put (1,"a");
accessOrder.put (3,"c");
accessOrder.put (2,"b");
v = accessOrder.get(3);

System.out.println(insertOrder);

System.out.println(accessOrder);

输出:
{1=a, 3=c, 2=b} // the last inserted key (2) is last
{1=a, 2=b, 3=c} // the most recently accessed key (3) is last

07-24 22:24