Java LinkedHashMap Example
LinkedHashMap 使用场景: 我们需要构建一个空间占用敏感的资源池,并且希望可以自动的释放掉不常访问的对象。
构造函数
/**
* Constructs an empty {@code LinkedHashMap} instance with the
* specified initial capacity, load factor and ordering mode.
*
* @param initialCapacity the initial capacity
* @param loadFactor the load factor
* @param accessOrder the ordering mode - {@code true} for
* access-order, {@code false} for insertion-order
* @throws IllegalArgumentException if the initial capacity is negative
* or the load factor is nonpositive
*/
public LinkedHashMap(int initialCapacity,
float loadFactor,
boolean accessOrder) {
super(initialCapacity, loadFactor);
this.accessOrder = accessOrder;
}
initialCapacity 默认值是16, loadFactor 默认值是0.75f, accessOrder默认值是false(也就是默认的ordering mode是insertion-order),如果把accessOrder 设置为true,这时候ordering mode 就是 access-order.
那么indertion-order 和access-order 有什么不同呢?
LinkedHashMap 提供了一个 removeEldestEntry 的方法:
/**
* Returns {@code true} if this map should remove its eldest entry.
* This method is invoked by {@code put} and {@code putAll} after
* inserting a new entry into the map. It provides the implementor
* with the opportunity to remove the eldest entry each time a new one
* is added. This is useful if the map represents a cache: it allows
* the map to reduce memory consumption by deleting stale entries.
*
* <p>Sample use: this override will allow the map to grow up to 100
* entries and then delete the eldest entry each time a new entry is
* added, maintaining a steady state of 100 entries.
* <pre>
* private static final int MAX_ENTRIES = 100;
*
* protected boolean removeEldestEntry(Map.Entry eldest) {
* return size() > MAX_ENTRIES;
* }
* </pre>
*
* <p>This method typically does not modify the map in any way,
* instead allowing the map to modify itself as directed by its
* return value. It <i>is</i> permitted for this method to modify
* the map directly, but if it does so, it <i>must</i> return
* {@code false} (indicating that the map should not attempt any
* further modification). The effects of returning {@code true}
* after modifying the map from within this method are unspecified.
*
* <p>This implementation merely returns {@code false} (so that this
* map acts like a normal map - the eldest element is never removed).
*
* @param eldest The least recently inserted entry in the map, or if
* this is an access-ordered map, the least recently accessed
* entry. This is the entry that will be removed it this
* method returns {@code true}. If the map was empty prior
* to the {@code put} or {@code putAll} invocation resulting
* in this invocation, this will be the entry that was just
* inserted; in other words, if the map contains a single
* entry, the eldest entry is also the newest.
* @return {@code true} if the eldest entry should be removed
* from the map; {@code false} if it should be retained.
*/
protected boolean removeEldestEntry(Map.Entry<K,V> eldest) {
return false;
}
这个方法默认返回false也就是说LinkedHashMap在新增键值对时LinkedHashMap并不会删除已有的“老的”元素,我们可以重写这个方法用来删除map里面最“老”的元素。
比如,如果我们希望在增加第4个元素时希望删掉它里面最“老”的元素。
在创建链表的时候重写该方法, return size() >3 的意思是:当LinkedHashMap里面的元素个数大于3时,就启动LinkedHashMap 删除最“老”元素的功能:
LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<>(16, 0.75f, true){
@Override
protected boolean removeEldestEntry(Map.Entry<String, String> eldest) {
return size() > 3;
}
};
我们给LinkedHashMap添加3个元素,然后通过foreach来打印它里面的所有元素。
linkedHashMap.put("project1", "1");
linkedHashMap.put("project2", "2");
linkedHashMap.put("project3", "3");
linkedHashMap.forEach((k, v) -> {
System.out.println("key: " + k + ", value: " + v);
});
输出结果:
key: project1, value: 1
key: project2, value: 2
key: project3, value: 3
这时候我们添加第4个元素,
linkedHashMap.put("project1", "1");
linkedHashMap.put("project2", "2");
linkedHashMap.put("project3", "3");
linkedHashMap.forEach((k, v) -> {
System.out.println("key: " + k + ", value: " + v);
});
linkedHashMap.put("project4", "4");
System.out.println("After changed;");
linkedHashMap.forEach((k, v) ->{
System.out.println("key: " + k + ", value: " + v);
});
输出结果:
key: project1, value: 1
key: project2, value: 2
key: project3, value: 3
After changed;
key: project2, value: 2
key: project3, value: 3
key: project4, value: 4
可以看到LinkedHashMap 把键值对("project1":"1")的元素删除了,新增了("project4":"4")的元素,元素的总数还是保持3个。
我们已经设置了LinkedHashMap的ordering mode 为access-order, 但是我们并没有访问LinkedHashMap任何其中的一个元素,所以在删除元素时,LinkHashMap删除了第一个被添加进去的元素。
我们试着访问下LinkedHashMap里面的元素,看看被删除的元素会是哪一个。
linkedHashMap.put("project1", "1");
linkedHashMap.put("project2", "2");
linkedHashMap.put("project3", "3");
linkedHashMap.forEach((k, v) -> {
System.out.println("key: " + k + ", value: " + v);
});
//访问了第一个元素
linkedHashMap.get("project1");
linkedHashMap.put("project4", "4");
System.out.println("After changed;");
linkedHashMap.forEach((k, v) ->{
System.out.println("key: " + k + ", value: " + v);
});
输出结果:
key: project1, value: 1
key: project2, value: 2
key: project3, value: 3
After changed;
key: project3, value: 3
key: project1, value: 1
key: project4, value: 4
可以看到第二个被添加进LinkedHashMap的元素被删除了。(第二个元素和第三个元素都没有被访问,但是第二个元素是先于第三个元素被添加到LinkedHashMap中的)。
我们可以得到如下结论:
如果没有重写LinkedHashMap removeEldestEntry方法,那么新添加元素时,它不会删除已经存在的元素。
如果重写了LinkedHashMap removeEldestEntry方法,accessOrder为false,当新添加元素时,它会删除Map里正存在的并且最早被添加进来的元素。
如果重写了LinkedHashMap removeEldestEntry方法, 并且accessOrder为true,当新添加元素时,(1)如果map里面有未被访问过的元素,它会删除未被访问过的所有元素里最早被添加进去的元素。(2)如果map里所有的元素都被访问过,它会删除最早被访问过的元素。
注意:
当 ordering mode是 insertion-order 时,更新(reinsert)一个已经存在的键值并不会改变insertion order.
当ordering mode是 access-order时,put, putIfAbsent,
get, getOrDefault, compute, computeIfAbsent,
computeIfPresent, merge 等方法都会改变 access order 的顺序。