HashMap保存键值对时是无序存放的,为了实现键值对的有序存储,JDK还提供了一个LinkedHashMap给我们使用。
LinkedHashMap有序存储示例:
package com.darkmi.basic;
import java.util.LinkedHashMap;
public class LinkedHashMapTest {
public static void main(String[] args) {
LinkedHashMap
linkedMap.put(new Integer(1), “aaa”);
linkedMap.put(new Integer(3), “bbb”);
linkedMap.put(new Integer(2), “ccc”);
linkedMap.put(new Integer(6), “ddd”);
linkedMap.put(new Integer(5), “eee”);
linkedMap.put(new Integer(4), “fff”);
System.out.println(linkedMap);
}
}
输出:
{1=aaa, 3=bbb, 2=ccc, 6=ddd, 5=eee, 4=fff}
如果换成HashMap,则不会以插入顺序进行输出:
package com.darkmi.basic;
import java.util.HashMap;
import java.util.Map;
public class LinkedHashMapTest {
public static void main(String[] args) {
Map
hashMap.put(new Integer(1), “aaa”);
hashMap.put(new Integer(3), “bbb”);
hashMap.put(new Integer(2), “ccc”);
hashMap.put(new Integer(6), “ddd”);
hashMap.put(new Integer(5), “eee”);
hashMap.put(new Integer(4), “fff”);
System.out.println(hashMap);
}
}
输出:
{1=aaa, 2=ccc, 3=bbb, 4=fff, 5=eee, 6=ddd}
LinkedHashMap有一个基于LRU算法的构造函数,使用该构造函数的LinkedHashMap还有一些额外的特性。
示例:
package com.darkmi.basic;
import java.util.LinkedHashMap;
public class LinkedHashMapTest {
public static void main(String[] args) {
LinkedHashMap
linkedMap.put(new Integer(1), “aaa”);
linkedMap.put(new Integer(2), “bbb”);
linkedMap.put(new Integer(3), “ccc”);
linkedMap.put(new Integer(4), “ddd”);
linkedMap.put(new Integer(5), “eee”);
linkedMap.put(new Integer(6), “fff”);
System.out.println(linkedMap);
//访问前两个元素
for (int i = 1; i < 3; i++) {
System.out.println(linkedMap.get(new Integer(i)));
}
System.out.println(linkedMap);
}
}
输出:
{1=aaa, 2=bbb, 3=ccc, 4=ddd, 5=eee, 6=fff}
aaa
bbb
{3=ccc, 4=ddd, 5=eee, 6=fff, 1=aaa, 2=bbb}
说明:
1、LRU算法:LRU是Least Recently Used的缩写,可以理解为用过的放到队列后边,没用过的放到队列前边。详细解释见维基百科。
2、LinkedHashMap构造函数中的16和0.75f是无参构造函数的默认值:
/**
* Constructs an empty insertion-ordered LinkedHashMap instance
* with the default initial capacity (16) and load factor (0.75).
*/
public LinkedHashMap() {
super();
accessOrder = false;
}
Sorry, the comment form is closed at this time.
加载因子怎么用啊?构造函数中的几个参数的意义是什么啊?