首先 LinkedHashMap是HashMap的一个子类,它保留插入的顺序,如果需要输出的顺序和输入时的相同,那么就选用LinkedHashMap。
LinkedHashMap的增删改查与hashmap无异,主要研究一个“保留插入顺序”的特性。
进入java.util源码包中,找到LinkedHashMap.java 可以看到LinkedHashMap的多个构造方法;
/**
* Constructs an empty insertion-ordered <tt>LinkedHashMap</tt> instance
* with the specified initial capacity and load factor.
*
* @param initialCapacity the initial capacity
* @param loadFactor the load factor
* @throws IllegalArgumentException if the initial capacity is negative
* or the load factor is nonpositive
*/
public LinkedHashMap(int initialCapacity, float loadFactor) {
super(initialCapacity, loadFactor);
accessOrder = false;
}
/**
* Constructs an empty insertion-ordered <tt>LinkedHashMap</tt> instance
* with the specified initial capacity and a default load factor (0.75).
*
* @param initialCapacity the initial capacity
* @throws IllegalArgumentException if the initial capacity is negative
*/
public LinkedHashMap(int initialCapacity) {
super(initialCapacity);
accessOrder = false;
}
/**
* Constructs an empty insertion-ordered <tt>LinkedHashMap</tt> instance
* with the default initial capacity (16) and load factor (0.75).
*/
public LinkedHashMap() {
super();
accessOrder = false;
}
/**
* Constructs an empty <tt>LinkedHashMap</tt> 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 - <tt>true</tt> for
* access-order, <tt>false</tt> 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: 基于插入顺序 true: 基于访问顺序
所以,通过demo来查看accessOrder 对LinkedHashMap的影响。
public static void main(String[] args) {
2 Map<String, String> map = new LinkedHashMap<String, String>(16,0.75f,true);
3 map.put("1", "a");
4 map.put("2", "b");
5 map.put("3", "c");
6 map.put("4", "e");
7
8 for (Iterator<String> iterator = map.values().iterator(); iterator
9 .hasNext();) {
10 String name = (String) iterator.next();
11 System.out.print(name);
12 }
13 }
accessOrder为true,正常插入打印结果为:abce;
public static void main(String[] args) {
2 Map<String, String> map = new LinkedHashMap<String, String>(16,0.75f,true);
3 map.put("1", "a");
4 map.put("2", "b");
5 map.put("3", "c");
6 map.put("4", "e");
7
8 //new add
9 map.get("1");
10 map.get("2");
11
12 for (Iterator<String> iterator = map.values().iterator(); iterator
13 .hasNext();) {
14 String name = (String) iterator.next();
15 System.out.print(name);
16 }
17 }
插入之后,对内容进行访问,LinkedHashMap会将最新访问的元素放在链尾。打印结果为ceab;