LinkedHashMap是HashMap的子类,唯一的区别在于LinkedHashMap对顺序的维护,是有序的
构造函数
public LinkedHashMap(int initialCapacity, float loadFactor) {
super(initialCapacity, loadFactor);
accessOrder = false;
}
public LinkedHashMap(int initialCapacity) {
super(initialCapacity);
accessOrder = false;
}
public LinkedHashMap() {
super();
accessOrder = false;
}
public LinkedHashMap(Map<? extends K, ? extends V> m) {
super(m);
accessOrder = false;
}
public LinkedHashMap(int initialCapacity,
float loadFactor,
boolean accessOrder) {
super(initialCapacity, loadFactor);
this.accessOrder = accessOrder;
}
构造函数参数容量,加载因子都继承hashMap,唯一的区分在于对于属性accessOrder的维护
/**
* The iteration ordering method for this linked hash map: <tt>true</tt>
* for access-order, <tt>false</tt> for insertion-order.
*
* @serial
*/
private final boolean accessOrder;
accessOrder字段表示对顺序的维护。true表示按照访问顺序,false表示按照插入顺序(插入可能不是在尾部顺序添加,可能是按照索引添加,顺序可能不一致)
LinkedHashMap构造默认是维护元素插入的顺序
linkedHashMap的数据结构的最小单元
private static class Entry<K,V> extends HashMap.Entry<K,V> {
// These fields comprise the doubly linked list used for iteration.
Entry<K,V> before, after;
Entry(int hash, K key, V value, HashMap.Entry<K,V> next) {
super(hash, key, value, next);
}
/**
* Removes this entry from the linked list.
*/
private void remove() {
before.after = after;
after.before = before;
}
在HashMap.Entry的基础上新增了两个属性before,after 表示 顺序上的前一个元素的地址和后一个元素的地址,而原next只是表示在一个数组位置处的链表上的,下一个元素位置。