前文:
首先你要耐心,最好有一定源码基础,没有也行下面也会教你怎么有效阅读源码。
其次为什么先讲List。因为建立再这个基础上去理解其他的东西,事半功倍。
原文件:
原文件链接,觉得有用下载
正文:
JAVA集合实现原理及其优化。
背景介绍:
这是基于jdk1.8分析的,主要是对java集合的实现源码分析。
Java集合框架:
注:上图参考百度结果。
除了上面的集合类型。我们还会将Stack(栈)、Node(树)、Quene(队列)、HashTable的源码实现和优化点。
1 List集合
该接口:
public interface List<E> extends Collection<E> {
int size();
boolean isEmpty();
boolean contains(Object o);
Object[] toArray();
<T> T[] toArray(T[] a);
boolean containsAll(Collection<?> c);
boolean addAll(Collection<? extends E> c);
boolean addAll(int index, Collection<? extends E> c);
boolean removeAll(Collection<?> c);
boolean retainAll(Collection<?> c);
default void replaceAll(UnaryOperator<E> operator) {
Objects.requireNonNull(operator);
final ListIterator<E> li = this.listIterator();
while (li.hasNext()) {
li.set(operator.apply(li.next()));
}
}
@SuppressWarnings({"unchecked", "rawtypes"})
default void sort(Comparator<? super E> c) {
Object[] a = this.toArray();
Arrays.sort(a, (Comparator) c);
ListIterator<E> i = this.listIterator();
for (Object e : a) {
i.next();
i.set((E) e);
}
}
void clear();
int hashCode();
E get(int index);
E set(int index, E element);
void add(int index, E element);
E remove(int index);
int indexOf(Object o);
int lastIndexOf(Object o);
ListIterator<E> listIterator();
ListIterator<E> listIterator(int index);
List<E> subList(int fromIndex, int toIndex);
}
逐一来看看它的实现类。
逐一来看看它的实现类。
1.2 ArrayList
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
由于该类方法太多,我们之分析关键的方法。
这里额外补充一点,所有list是有序的,就是它插入的顺序。但是他的里面的元素是无序。以下说的无序是指元素本身没有自然顺序(指定顺序除外)
该类的说明:
1、无序不唯一
上面可知ArrayList的继承和实现关系。
基础的默认创建、指定大小创建,是很基础的东西。来看看由该类的三个构造器
创建的List。
//默认创建一个ArrayList集合
List<String> list = new ArrayList<>();
//创建一个初始化长度为100的ArrayList集合
List<String> initlist = new ArrayList<>(100);
//将其他类型的集合转为ArrayList
List<String> setList = new ArrayList<>(new HashSet());
前两个构造器:
/**
* 纯空数组,但是指定长度
*/
private static final Object[] EMPTY_ELEMENTDATA = {};
/**
* 纯空数组,默认长度
*/
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
/**
* 对象数组
*/
transient Object[] elementData;
/**
* 构造得到一个有指定长度的数组
*/
public ArrayList(int initialCapacity) {
if (initialCapacity > 0) {
this.elementData = new Object[initialCapacity];
} else if (initialCapacity == 0) {
this.elementData = EMPTY_ELEMENTDATA;
} else {
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
}
}
/**
* 构造得到一个初始长度为10的数组.
*/
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
由于ArrayList之上多重继承中有实现了Collection。也就是提供了将Collection下的LinkedList、HashSet、LinkedHashSet、TreeSet转为ArrayList。
public ArrayList(Collection<? extends E> c) {
elementData = c.toArray();
if ((size = elementData.length) != 0) {
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
} else {
// replace with empty array.
this.elementData = EMPTY_ELEMENTDATA;
}
}
上面的实现其实不难,是Arrays.copyOf方法的利用。
比如:
List<String> linklist = new ArrayList<>(new LinkedList<>());
List<String> treelist = new ArrayList<>(new TreeSet<>());
List<String> linktreelist = new ArrayList<>(new LinkedHashSet<String>());
这样的实现大大方便了我们的集合转换。
1.2.1 ArrayList的扩容机制。
总体来说,分为两步扩容和添加元素。
扩容:扩大数组的长度(这是核心)。就是把原来的数组复制到空间更大的数组中去。
添加元素:将新元素添加到扩容后的数组。
每次添加新元素将调用:
public boolean add(E e) {
// 确保添加容量
ensureCapacityInternal(size + 1); // Increments modCount!!
// 将新元素加入数组
elementData[size++] = e;
return true;
}
private void ensureCapacityInternal(int minCapacity) {
// 确保容量
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
// 计算最小容量
private static int calculateCapacity(Object[] elementData, int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
return minCapacity;
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
// 扩容的实现
private void grow(int minCapacity) {
int oldCapacity = elementData.length;
// oldCapacity >> 1 右移运算符 扩容为原来的1.5倍
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);
}
// 该方法决定了ArrayList的最大长度 MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
到此ArrayList扩容的扩容就看完了。其实不难发现,ArrayList本质就是一个可以动态变法的数组。
对ArrayList的维护:
其实就如数组的更新删除插入获取的操作逻辑一样。这个没什么可说的。需要考虑插更新删除插入获取index是否越界。
ArrayList优化:
其实ArrayList几乎完美,我们所说的优化,只是从项目的角度来看。我们唯一能做到的就是减少ArrayList扩容。
我们来做个测试:
package com.design.cor;
import java.util.*;
public class Main {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
long time1 = System.currentTimeMillis();
for (int i = 1; i < 1000000; i++) {
list.add(i);
}
long time2 = System.currentTimeMillis();
System.out.println("放任扩容: " + (time2 - time1));
List<Integer> list1 = new ArrayList<>(1000000);
long time21 = System.currentTimeMillis();
for (int i = 1; i < 1000000; i++) {
list1.add(i);
}
long time22 = System.currentTimeMillis();
System.out.println("指定容量: " + (time22 - time21));
}
}
结果如下:
原因显而易见:初始10要经历10*(1.5)^29 ≈ 1278430 次扩容才能达到需求。而第二个我们就指定了大小。结论显而易见,处于系统性能考虑大数据量下,需要预估大小,并指定。
这里还有个值得说的点。你会发现所有集合都有求集合差集和并集的操作:
package com.design.cor;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
public class Main {
public static void main(String[] args){
List<Integer> list1 = new ArrayList<>();
list1.add(1);
list1.add(2);
list1.add(3);
list1.add(4);
List<Integer> list2 = new ArrayList<>();
list2.add(1);
list2.add(4);
list2.add(7);
list2.add(10);
// 求并集
List<Integer> listAll = new ArrayList<>();
listAll.addAll(list1);
listAll.addAll(list2);
// 有序去重
listAll = new ArrayList<Integer> (new LinkedHashSet<>(listAll));
System.out.println("并集为: " + listAll);
// 差集
listAll.removeAll(list1);
System.out.println("差集为: " + listAll);
}
}
运行结果:
其他的集合也是类似的。不一一再举例子。
1.3 LinkedList
以双向链表实现的List,它除了作为List使用,还可以作为队列或者堆栈使用。(怎么突然就是链表了呢)
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable
该类的说明:
1、有序,不唯一。
如上,对比下ArrayList
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
很明显差距就在继承类上和实现类上。由于方法非常的多,以下我们只列出我么所关心的方法。
我们来看看在LinkedList中双向链表的定义。
内部内实现的双向链表:
private static class Node<E> {
E item;
Node<E> next;
Node<E> prev;
Node(Node<E> prev, E element, Node<E> next) {
this.item = element;
this.next = next;
this.prev = prev;
}
}
如果不出我们所料,LinkedList就是在维护这个对象。
/**
* Constructs an empty list.
*/
public LinkedList() {
}
// 完成collection下list之间的转换
public LinkedList(Collection<? extends E> c) {
// 得到当前对象
this();
// 将所有的值添加进去
addAll(c);
}
在作如下解释前,我发现
/**
* Pointer to first node.
* Invariant: (first == null && last == null) ||
* (first.prev == null && first.item != null)
*/
transient Node<E> first;
/**
* Pointer to last node.
* Invariant: (first == null && last == null) ||
* (last.next == null && last.item != null)
*/
transient Node<E> last;
transient修饰符如下解释:
1)transient修饰的变量不能被序列化;
2)transient只作用于实现 Serializable 接口;
3)transient只能用来修饰普通成员变量字段;
4)不管有没有 transient 修饰,静态变量都不能被序列化;
回到正文,为什么我们要将上面的frist和last对象拿出来说,他们是双向链表的头尾,很多的LinkenList方法就是基于他们来实现。
如果对链表的操作不清除。建议看数据结构的书。这里简单说明下,链表的维护就是节点维护,比如删除一个元素,将后元素的头节点指向前元素的。
先分析下加入一个元素。
这里我不得不吐槽下IDEA对源码很不友好。测试代码我们就在eclispe来分析。
/**
* Appends the specified element to the end of this list.
*/
public boolean add(E e) {
linkLast(e);
return true;
}
/**
* Links e as last element.
*/
void linkLast(E e) {
final Node<E> l = last;
final Node<E> newNode = new Node<>(l, e, null);
last = newNode;
if (l == null)
first = newNode;
else
l.next = newNode;
size++;
modCount++;
}
测试程序:
package zy.stu.com;
import java.util.LinkedList;
import java.util.List;
public class MapIt {
public static void main(String[] args) {
List<Integer> list = new LinkedList<>();
list.add(111);
list.add(123);
}
}
添加测试截图:
首先这个E e是什么,debug下不难发现它的类型居然是个LinkedList,这就导致了最后的结果看起来怪怪的?
上面的结果你觉得怪吗?其中确实只有两个,但这是个双向链表,无限可循环。但是你可以id发现42-33-42-33-42-33。所以这是正常的。
链表的插入,懒得画了借用百度图片。
如上,剩下的删除、插入指定位置、更新、获取操作,其实都是在对Node进行维护处理。
移除一个元素:
public E remove(int index) {
checkElementIndex(index);
return unlink(node(index));
}
/**
* Returns the (non-null) Node at the specified element index.
* 返回要删除节点
*/
Node<E> node(int index) {
// assert isElementIndex(index);
if (index < (size >> 1)) {
Node<E> x = first;
for (int i = 0; i < index; i++)
x = x.next;
return x;
} else {
Node<E> x = last;
for (int i = size - 1; i > index; i--)
x = x.prev;
return x;
}
}
/**
* Unlinks non-null node x.
* 删除节点、修改节点指向
*/
E unlink(Node<E> x) {
// assert x != null;
final E element = x.item;
final Node<E> next = x.next;
final Node<E> prev = x.prev;
if (prev == null) {
first = next;
} else {
prev.next = next;
x.prev = null;
}
if (next == null) {
last = prev;
} else {
next.prev = prev;
x.next = null;
}
x.item = null;
size--;
modCount++;
return element;
}
看上面代码很简单对!就是对链表的删除节点维护。
获取元素:就能简单了,这就是删除元素的查找结点。
public E get(int index) {
checkElementIndex(index);
return node(index).item;
}
总结:
1、链表不存初始大小、也没有扩容机制。
2、链表的实现,注定了获取效率不高,适合大数据量下的插入和删除且不关注查询。(因为查询一个要从头开始查找)。
3、额外补充,它实现了queue的方法,你也用queue的方法操作该list
2 Set集合
2.1 HashSet
public class HashSet<E>
extends AbstractSet<E>
implements Set<E>, Cloneable, java.io.Serializable
没什么可说。说说源码中对该类的介绍:
1、由hash表实现,但实际上是个HashMap,允许null值、无序、不重复。
我们来看看它是怎么维护的list。
// 这个是关键,它维护就是这个HashHap
private transient HashMap<E,Object> map;
// 关联回溯的值
private static final Object PRESENT = new Object();
/**
构造一个新的空集; 支持<tt> HashMap </ tt>实例具有
默认初始容量(16)和负载系数(0.75)。
*/
public HashSet() {
map = new HashMap<>();
}
/**
* 构建一个传入Collection下的结合得到新的集合,默认加载因子0.75,其实就是空map加入元素
* @param c 其他Collection下的集合
*/
public HashSet(Collection<? extends E> c) {
map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16));
addAll(c);
}
/**
自己指定初始容量和加载因子创建
*/
public HashSet(int initialCapacity, float loadFactor) {
map = new HashMap<>(initialCapacity, loadFactor);
}
/**
* 指定初始容量构建
*/
public HashSet(int initialCapacity) {
map = new HashMap<>(initialCapacity);
}
/**
* 构造LinkedHashMap,专门为LinkedHashMap提供
*/
HashSet(int initialCapacity, float loadFactor, boolean dummy) {
map = new LinkedHashMap<>(initialCapacity, loadFactor);
}
由此可见它的原理还得看HashMap才能知道,详细参考HashMap解释。
再说一次,原理这里不做详细说明。
既然如此这里我们就关注map,如何对这个map进行维护的就行。
添加:
// 添加元素无则添加、有则不变返回。元素为key,value为空对象PRESENT为value
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
移除一个元素:
// object,其实就是根据o为key移除
public boolean remove(Object o) {
return map.remove(o)==PRESENT;
}
其实看上了上面添加和删除,我想包含你就能想到它是怎么实现的了。
这个不用看吧?就是在维护这个HashMap的key
包含:
// 判断map中是否含这个key
public boolean contains(Object o) {
return map.containsKey(o);
}
大小size:就更简单了,就是map的大小嘛。
public int size() {
return map.size();
}
// 判空
public boolean isEmpty() {
return map.isEmpty();
}
// 清空map中的元素。
public void clear() {
map.clear();
}
2.2 LinkedHashSet
public class LinkedHashSet<E>
extends HashSet<E>
implements Set<E>, Cloneable, java.io.Serializable {
看看对该类说明:
1、数据唯一,还有序。
如果还有对上面HashSet有印象,LinkedHashSet在HashSet是已提供?实际就是如此,看如下该类就这么点内容:
public class LinkedHashSet<E>
extends HashSet<E>
implements Set<E>, Cloneable, java.io.Serializable {
private static final long serialVersionUID = -2851667679971038690L;
/**
* 指定初始容量和加载因子,其实是父类的
*/
public LinkedHashSet(int initialCapacity, float loadFactor) {
super(initialCapacity, loadFactor, true);
}
/**
* 构造指定初始容量,默认加载因子0.75
*/
public LinkedHashSet(int initialCapacity) {
super(initialCapacity, .75f, true);
}
/**
* 默认初始容量16,默认加载因子0.75
*/
public LinkedHashSet() {
super(16, .75f, true);
}
/**
* 传入Collection下集合构造LinkedHashSet,初始容量为原先的2倍,0.75加载因子
*/
public LinkedHashSet(Collection<? extends E> c) {
super(Math.max(2*c.size(), 11), .75f, true);
addAll(c);
}
@Override
public Spliterator<E> spliterator() {
return Spliterators.spliterator(this, Spliterator.DISTINCT | Spliterator.ORDERED);
}
}
所以上面的本质实现是LinkedHashMap如下:
在HashSet类中,返回LinkedHashMap。
HashSet(int initialCapacity, float loadFactor, boolean dummy) {
map = new LinkedHashMap<>(initialCapacity, loadFactor);
}
他如何做到有序,不唯一。这里暂时不分析。
对该类而言,重点就来,你发现和上面没什么区别了,还是在那个map进行维护。
到此不再累述。
2.3 TreeSet
public class TreeSet<E> extends AbstractSet<E>
implements NavigableSet<E>, Cloneable, java.io.Serializable
首先,你联想下上面的,你是不是已经get了?我们猜一下,其实是对TreeMap的key维护。
该类的说明:
1、基础类型自然排序,存时储对象时需要指定排序Comparable,否则异常。这个比较算法没什么可说把,就像二维数组的排序一样。在方法内定义比较算法, 根据大小关系, 返回正数负数或零。
2、利用实现NavigableMap、TreeMap实现;
然而他出乎我们的预料。
/**
* The backing map. 具有了针对给定搜索目标返回最接近匹配项的导航
*/
private transient NavigableMap<E,Object> m;
private static final Object PRESENT = new Object();
他所维护的对象是NavigableMap<E, Object>。
来看看他的构造器:
/**
* 构造得到 navigable map.
*/
TreeSet(NavigableMap<E,Object> m) {
this.m = m;
}
/**
* 构造一个空树
*/
public TreeSet() {
this(new TreeMap<E,Object>());
}
/**
* 构造一个我们按照规则排序的集合
*/
public TreeSet(Comparator<? super E> comparator) {
this(new TreeMap<>(comparator));
}
/**
* 将Collection下其他类型转为TreeSet
*/
public TreeSet(Collection<? extends E> c) {
this();
addAll(c);
}
/**
* Constructs a new tree set containing the same elements and
* using the same ordering as the specified sorted set.
*/
public TreeSet(SortedSet<E> s) {
this(s.comparator());
addAll(s);
}
方法上而言,和上面的LinkedHashSet一样。都是对map的key的维护,就不需要再累述。
2 map
map是key、value的集合,下有HashMap、ConcurrentHashMap、LinkedHashMap、TreeMap。
有了List的种种引子。你是否发现map显得是那么那么的重要。
public interface Map<K,V> {
Map的接口没什么可看的,接口嘛,就是定义一些方法。主要还得看实现类。
2.1 HashMap
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable {
该类说明:
1、通常是hash表实现,但存储过大,将转为TreeNode实现。通常是先使用hash表,再合适时转为TreeNode。
也还有treeNode的说明,下面看代码说明问题。需要说明一点由于map的重要性,叙述的内容应该很多也很重要。
该类的属性:
/**
* 初始容量16 这个容量为2的倍数
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
/**
* 最大容量 2^30
*/
static final int MAXIMUM_CAPACITY = 1 << 30;
/**
* 默认负载因子.
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
/**
* 界限值大于8时hash表转为红黑树。至少是8
*/
static final int TREEIFY_THRESHOLD = 8;
/**
* 当小于6时,红黑树转为hash表
*/
static final int UNTREEIFY_THRESHOLD = 6;
/**
* 最小树形化阈值:至少4 * TREEIFY_THRESHOLD = 64。为了避免hash碰撞。
*/
static final int MIN_TREEIFY_CAPACITY = 64;
上面的属性哪里用,先放一放。接下来属性,需要知道内部静态类Node<K,V>的实现:
首先要看下Map.Entry<K,V>接口:(具体还得看实现类)
主要看其中的排序方法:
interface Entry<K,V> {
K getKey();
V getValue();
V setValue(V value);
boolean equals(Object o);
int hashCode();
// 按key默认排序
public static <K extends Comparable<? super K>, V> Comparator<Map.Entry<K,V>> comparingByKey() {
return (Comparator<Map.Entry<K, V>> & Serializable)
(c1, c2) -> c1.getKey().compareTo(c2.getKey());
}
// 按value默认排序
public static <K, V extends Comparable<? super V>> Comparator<Map.Entry<K,V>> comparingByValue() {
return (Comparator<Map.Entry<K, V>> & Serializable)
(c1, c2) -> c1.getValue().compareTo(c2.getValue());
}
// 按key的指定算法排序
public static <K, V> Comparator<Map.Entry<K, V>> comparingByKey(Comparator<? super K> cmp) {
Objects.requireNonNull(cmp);
return (Comparator<Map.Entry<K, V>> & Serializable)
(c1, c2) -> cmp.compare(c1.getKey(), c2.getKey());
}
// 按value的指定算法排序
public static <K, V> Comparator<Map.Entry<K, V>> comparingByValue(Comparator<? super V> cmp) {
Objects.requireNonNull(cmp);
return (Comparator<Map.Entry<K, V>> & Serializable)
(c1, c2) -> cmp.compare(c1.getValue(), c2.getValue());
}
}
内部静态类Node<K,V>:作用想一个元素,一个元素四个值key、value、hash、Node<K,V>对象。
这里里面的东西都很重,着重理解。
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
Node(int hash, K key, V value, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next; // 用来解决hash碰撞的
}
//将实现的方法final了以及属性final,这很好理解,为了保证当前Node的key和hash值唯一
public final K getKey() { return key; }
public final V getValue() { return value; }
public final String toString() { return key + "=" + value; }
// hash值计算 key得hash值和valuehash值得次方
public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}
// 经典处理呀,hashcode和equals方法重写。
// 这里的重写充分利用final的性质
public final boolean equals(Object o) {
if (o == this)
return true;
if (o instanceof Map.Entry) {
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
if (Objects.equals(key, e.getKey()) &&
Objects.equals(value, e.getValue()))
return true;
}
return false;
}
}
关于Objects下:
public static int hashCode(Object o) {
return o != null ? o.hashCode() : 0;
}
object下:
public native int hashCode();
看到这里,发挥你的想象力。猜测一下,它是在维护一个什么样的东西。
我大胆猜下。
一、维护Node<K,V>数组,用Node<K,V> next来链表法解决hash碰撞,数组的每个项又是一个链表。
二、阈值超过8呢?是不是Node<K,V>直接构成一个红黑树呢。
/**
* 首次初始Node<K,V>[]数组,长度为2的倍数,也就是如我们猜想,要维护的对象了啦
*/
transient Node<K,V>[] table;
// 也有一些是我想不到的,不如下面的缓存
/**
* entrySet缓存key和value
*/
transient Set<Map.Entry<K,V>> entrySet;
/**
* map的大小
*/
transient int size;
/**
* 此map的修改次数,用于hashmap故障快速定位
*/
transient int modCount;
/**
* 调整大小时的下一个大小值(容量*负载系数)
*/
int threshold;
/**
* hash表的负载因子.
*/
final float loadFactor;
到此我们要用的属性,基本介绍完了。如上的猜想。有对也有不对。
这里记录下个人想法:逻辑一定要先行,猜也好,推也好。边看边推也好。一定是思维先行,而不是像机器一样被动接受。
接着看看构造器:
/**
* 构造指定初始容量和负载因子的HashMap
*/
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
this.loadFactor = loadFactor;
// 对于给定容量返回两倍大小
this.threshold = tableSizeFor(initialCapacity);
}
/**
* 构造指定初始容量和默认负载因子0.75
*/
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
/**
* 构建初始容量16和负载因子为0.75的HashMap
*/
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR;
}
/**
* map下相互转化的构造器
*/
public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
// 上面先构造,下面放入
putMapEntries(m, false);
}
就从构造方法总体而言。
1、为什么所有集合都是有指定大小的构造?
答:这是一种常见的优化手段,指定容量可以防止不停扩容导致的效率问题。这也是为什么编码建议上给出:初始化集合时,如果已知集合的数量,那么一定要在初始化时设置集合的容量大小,这样就可以有效的提高集合的性能。
2、集合大小随便指定的吗?
这个问题先留着?带着这个问题,先将剩下集合分析完。
我们来看看是如何维护。
添加:
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
static final int hash(Object key) {
int h;
// 由此可知key为null
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
/**
* @param hash 由key计算的hash值
* @param key key
* @param value vlaue
* @param onlyIfAbsent 如果为true则不改变已有的value值
* @param evict 如果为true表处于创建模式
*/
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
// 这n的复用。学到了。
// 为空或不存在则初始化容器,并拿到容器的大小
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
// 这i的复用也恐怖。
// tab数组hash规则下为null,这将这个null赋值
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
// 该位置不为null
else {
Node<K,V> e; K k;
// 当前元素key是一致,将value替换即可
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
// 是红黑树,则添加
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
// 那么就是链表
else {
// 循环查找 e的复用
for (int binCount = 0; ; ++binCount) {
// 找到末尾还没有,再尾部插入。
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
// 循环链表有hash值和key值相同的,赋值value
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
// existing mapping for key
if (e != null) {
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
// 如果当前HashMap的容量超过threshold则进行扩容
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
// 初始化或两倍增加容量 是扩容机制核心方法
// 上面的逻辑很清楚:HashMap初始化后首次插入数据时,先发生resize扩容再插入数据,之后每当插入的数据个数达到// threshold时就会发生resize,此时是先插入数据再resize。
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
// 是否已扩容过
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
if (oldCap > 0) {// 扩容过
if (oldCap >= MAXIMUM_CAPACITY) {// 超过最大容量
threshold = Integer.MAX_VALUE;
return oldTab;
}
// 大于初始容量,不超过最大容量,table的容量乘以2。这里复用了
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
// threshold的值也乘以2
newThr = oldThr << 1; // double threshold
}
// 默认构造器下进行扩容
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
// 使用带有初始容量的构造器在此处进行扩容
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
// 扩容2倍
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
// 将oldTab赋值给newTab
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
// 这个赋值和上面基本一样的。
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { // preserve order
// 链表处理:为了提高效率,分成两个链表
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
next = e.next;
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
else {
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
上面这些方法一定要懂
–核心:
1、resize方法,扩容都是按2的幂次方扩容的。
再来看看get方法:理解了添加,获取我想不难理解。
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
// 始终从第一个开始匹配,第一个匹配返回
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) {
// 是红黑树,从根结点查询是否匹配,匹配则返回
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {// 链表,循环查找匹配结果
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
了解了添加和获取。移除就很容易了。就是找到它,移除。
移除:如果你细心发现移除是有返回值的哟。
public V remove(Object key) {
Node<K,V> e;
return (e = removeNode(hash(key), key, null, false, true)) == null ?
null : e.value;
}
final Node<K,V> removeNode(int hash, Object key, Object value,
boolean matchValue, boolean movable) {
Node<K,V>[] tab; Node<K,V> p; int n, index;
if ((tab = table) != null && (n = tab.length) > 0 &&
(p = tab[index = (n - 1) & hash]) != null) {
Node<K,V> node = null, e; K k; V v;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
node = p;
else if ((e = p.next) != null) {
if (p instanceof TreeNode) // 红黑树的查找
node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
else {
do {
// 链表的查找
if (e.hash == hash &&
((k = e.key) == key ||
(key != null && key.equals(k)))) {
node = e;
break;
}
p = e;
} while ((e = e.next) != null);
}
}
// 删除操作
if (node != null && (!matchValue || (v = node.value) == value ||
(value != null && value.equals(v)))) {
if (node instanceof TreeNode) // 红黑树的删除
((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
else if (node == p)
tab[index] = node.next; // 数组删除
else
p.next = node.next; // 链表的删除
++modCount;
--size;
afterNodeRemoval(node);
return node;
}
}
return null;
}
其他的方法,都是类似的处理了。这里举个例子containsKey方法:
public boolean containsKey(Object key) {
return getNode(hash(key), key) != null;
}
他就是去获取,获取不到就是没有了。
其他的方法,我想用用上面逻辑,就可以想得通。
上面的代码你看了,它是如何解决hash碰撞的是否有了一个概念?
在JDK7中有再hash、死循环、死锁的问题,在jdk8已经优化,都是利用数组+链表+红黑树避免的,逻辑如上。
大致逻辑:先查看数组—是否为红黑树—链表的处理。
1、hash的处理。
上面有个方法,这个hash值是通过hash方法算出来。p = tab[i = (n - 1) & hash]) == null这是有没有hash碰撞,没有就直接创建newNode。
2、出现了hash碰撞:
是红黑树,从根结点查找,有则赋值,没有则在尾部添加。
是链表,从迭代查找,有则赋值,没有则添加,添加需要判定链表转红黑树的契机。
为什么避免了死循环。上面的添加,查找都有明显结束标志。
备注:里面红黑树的转化,这里是没讲的。
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
resize();
else if ((e = tab[index = (n - 1) & hash]) != null) {
TreeNode<K,V> hd = null, tl = null;
do {
TreeNode<K,V> p = replacementTreeNode(e, null);
if (tl == null)
hd = p;
else {
p.prev = tl;
tl.next = p;
}
tl = p;
} while ((e = e.next) != null);
if ((tab[index] = hd) != null)
hd.treeify(tab);
}
}
2 LinkedHashMap
public class LinkedHashMap<K,V>
extends HashMap<K,V>
implements Map<K,V>
{
你这一看大概就知道了。你可以大胆猜测构造器都是调的父类构造器。甚至里面的很多方法实现应该都是。但我们是知道的LinkedHashMap是有序的。所以将方法过一眼,重点开下如何保证有序的。
看看属性:
/**
* 该双链表的头
*/
transient LinkedHashMap.Entry<K,V> head;
/**
* 双链表的尾
*/
transient LinkedHashMap.Entry<K,V> tail;
构造方法:(举个例子说明问题)其他来自父类的构造器类似处理
/**
* 默认初始容量16和负载因子0.75.并指定accessOrder = false有序
*/
public LinkedHashMap() {
super();
accessOrder = false;
}
方法:
1、该类中,你根本找不到get、put、remove。都是父类的。这就不再累述。
2、如何保证有序的。
这个静态内部内类中,加了两个属性来保证有序。
/**
* HashMap.Node subclass for normal LinkedHashMap entries.
*/
static class Entry<K,V> extends HashMap.Node<K,V> {
Entry<K,V> before, after;
Entry(int hash, K key, V value, Node<K,V> next) {
super(hash, key, value, next);
}
}
// 新加一个元素放在末尾
Node<K,V> newNode(int hash, K key, V value, Node<K,V> e) {
LinkedHashMap.Entry<K,V> p =
new LinkedHashMap.Entry<K,V>(hash, key, value, e);
linkNodeLast(p);
return p;
}
private void linkNodeLast(LinkedHashMap.Entry<K,V> p) {
LinkedHashMap.Entry<K,V> last = tail;
tail = p;
if (last == null)
head = p;
else {
p.before = last;
last.after = p;
}
}
上面的是数组的操作,里面同样有类似的方法去处理红黑树和链表。
比如:
TreeNode<K,V> newTreeNode(int hash, K key, V value, Node<K,V> next) {
TreeNode<K,V> p = new TreeNode<K,V>(hash, key, value, next);
linkNodeLast(p);
return p;
}
不再累述,都是类似的逻辑。
3 TreeMap
public class TreeMap<K,V>
extends AbstractMap<K,V>
implements NavigableMap<K,V>, Cloneable, java.io.Serializable
NavigableMap<K,V>这个眼熟吧。前面TreeSet的时候说过在这里来分析。
来看看这个接口的说明:
public interface NavigableMap<K,V> extends SortedMap<K,V>
说明:
1、继承了SortedMap,重点在里面的排序方法。
2、是由红黑树实现。来自于Map.Entry<K,V>
回到TreeMap,来看看属性:
// 用于维护树形图中的顺序
private final Comparator<? super K> comparator;
// 根结点
private transient Entry<K,V> root;
/**
* 元素数量
*/
private transient int size = 0;
/**
* 该树被修改的次数
*/
private transient int modCount = 0;
看看构造方法:
// 构造默认自然排序
public TreeMap() {
comparator = null;
}
/**
* 构造指定按key的排序规则
*/
public TreeMap(Comparator<? super K> comparator) {
this.comparator = comparator;
}
/**
* map接口下其他的转为TreeMap,按key自然排序
*/
public TreeMap(Map<? extends K, ? extends V> m) {
comparator = null;
putAll(m);
}
/**
* 构造一个指定排序的TreeMap
*/
public TreeMap(SortedMap<K, ? extends V> m) {
comparator = m.comparator();
try {
buildFromSorted(m.size(), m.entrySet().iterator(), null, null);
} catch (java.io.IOException cannotHappen) {
} catch (ClassNotFoundException cannotHappen) {
}
}
这个TreeMap到底在维护这个东东啊?上面的属性上而言只剩一个东西了?
难道就是在维护这个Entry<K,V> root.就是红黑树。
该树的结构:
1、你需要理解的一个点是该类为 static final
static final class Entry<K,V> implements Map.Entry<K,V> {
K key;
V value;
Entry<K,V> left; // 左子树
Entry<K,V> right; // 右子树
Entry<K,V> parent;
boolean color = BLACK; // 不是黑就是红
/**
* 唯一设置K-V,和父节点
*/
Entry(K key, V value, Entry<K,V> parent) {
this.key = key;
this.value = value;
this.parent = parent;
}
/**
* Returns the key.
*/
public K getKey() {
return key;
}
/**
* Returns the value associated with the key.
*/
public V getValue() {
return value;
}
/**
* Replaces the value currently associated with the key with the given
* value.
*/
public V setValue(V value) {
V oldValue = this.value;
this.value = value;
return oldValue;
}
// 重写equals和hashCode
public boolean equals(Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
return valEquals(key,e.getKey()) && valEquals(value,e.getValue());
}
public int hashCode() {
int keyHash = (key==null ? 0 : key.hashCode());
int valueHash = (value==null ? 0 : value.hashCode());
return keyHash ^ valueHash;
}
public String toString() {
return key + "=" + value;
}
}
看看添加方法:
public V put(K key, V value) {
Entry<K,V> t = root;
if (t == null) {
// 为null 情况下,检查key
compare(key, key); // type (and possibly null) check
// 该结点保存K-V,以及父节点对象Entry<>
root = new Entry<>(key, value, null);
size = 1;
modCount++;
return null;
}
// 不为null
int cmp;
// 父节点
Entry<K,V> parent;
Comparator<? super K> cpr = comparator;
// 排序规则有
if (cpr != null) {
do {
parent = t;
cmp = cpr.compare(key, t.key);
if (cmp < 0)
t = t.left;
else if (cmp > 0)
t = t.right;
else
return t.setValue(value);
} while (t != null);
} // 排序规则无
else {
if (key == null)
throw new NullPointerException();
@SuppressWarnings("unchecked")
Comparable<? super K> k = (Comparable<? super K>) key;
do {
parent = t;
cmp = k.compareTo(t.key);
// 当前变量的左右子树,为什么可以这样写?是因为TreeMap的key是有序的。
if (cmp < 0)
t = t.left;
else if (cmp > 0)
t = t.right;
else
// 找到相同key,修改值
return t.setValue(value);
} while (t != null);
}
// 走到了左或右子树的末尾,创建节点,并设值给prrent左或右节点设值
Entry<K,V> e = new Entry<>(key, value, parent);
if (cmp < 0)
parent.left = e;
else
parent.right = e;
// 红黑设置
fixAfterInsertion(e);
size++;
modCount++;
return null;
}
// 这方法不想看,一堆旋转处理,太难理解了。我认为真的没有必要看。
private void fixAfterInsertion(Entry<K,V> x) {
x.color = RED;
while (x != null && x != root && x.parent.color == RED) {
if (parentOf(x) == leftOf(parentOf(parentOf(x)))) {
Entry<K,V> y = rightOf(parentOf(parentOf(x)));
if (colorOf(y) == RED) {
setColor(parentOf(x), BLACK);
setColor(y, BLACK);
setColor(parentOf(parentOf(x)), RED);
x = parentOf(parentOf(x));
} else {
if (x == rightOf(parentOf(x))) {
x = parentOf(x);
rotateLeft(x);
}
setColor(parentOf(x), BLACK);
setColor(parentOf(parentOf(x)), RED);
rotateRight(parentOf(parentOf(x)));
}
} else {
Entry<K,V> y = leftOf(parentOf(parentOf(x)));
if (colorOf(y) == RED) {
setColor(parentOf(x), BLACK);
setColor(y, BLACK);
setColor(parentOf(parentOf(x)), RED);
x = parentOf(parentOf(x));
} else {
if (x == leftOf(parentOf(x))) {
x = parentOf(x);
rotateRight(x);
}
setColor(parentOf(x), BLACK);
setColor(parentOf(parentOf(x)), RED);
rotateLeft(parentOf(parentOf(x)));
}
}
}
root.color = BLACK;
}
所有它所维护就是这棵树。
get方法: 懂了上面的添加,查找就很容易理解。就是树查找。
public V get(Object key) {
Entry<K,V> p = getEntry(key);
return (p==null ? null : p.value);
}
final Entry<K,V> getEntry(Object key) {
// Offload comparator-based version for sake of performance
if (comparator != null)
return getEntryUsingComparator(key);
if (key == null)
throw new NullPointerException();
@SuppressWarnings("unchecked")
Comparable<? super K> k = (Comparable<? super K>) key;
Entry<K,V> p = root;
while (p != null) {
// 因为key有序,才能这么写
int cmp = k.compareTo(p.key);
if (cmp < 0)
p = p.left;
else if (cmp > 0)
p = p.right;
else
return p;
}
return null;
}
remove方法:就是在get方法上多了删除的操作:
public V remove(Object key) {
Entry<K,V> p = getEntry(key);
if (p == null)
return null;
V oldValue = p.value;
deleteEntry(p);
return oldValue;
}
//删除 注释的很全面,不多说。如果你知晓二叉树是如何删除一个节点的,下面的过程你可以不用看了
private void deleteEntry(Entry<K,V> p) {
modCount++;
size--;
// If strictly internal, copy successor's element to p and then make p
// point to successor.
if (p.left != null && p.right != null) {
Entry<K,V> s = successor(p);
p.key = s.key;
p.value = s.value;
p = s;
} // p has 2 children
// Start fixup at replacement node, if it exists.
Entry<K,V> replacement = (p.left != null ? p.left : p.right);
if (replacement != null) {
// Link replacement to parent
replacement.parent = p.parent;
if (p.parent == null)
root = replacement;
else if (p == p.parent.left)
p.parent.left = replacement;
else
p.parent.right = replacement;
// Null out links so they are OK to use by fixAfterDeletion.
p.left = p.right = p.parent = null;
// Fix replacement
if (p.color == BLACK)
fixAfterDeletion(replacement);
} else if (p.parent == null) { // return if we are the only node.
root = null;
} else { // No children. Use self as phantom replacement and unlink.
if (p.color == BLACK)
fixAfterDeletion(p);
if (p.parent != null) {
if (p == p.parent.left)
p.parent.left = null;
else if (p == p.parent.right)
p.parent.right = null;
p.parent = null;
}
}
}
当然里面还有很多方法。但是基本元素的操作,都是基于上面三种方法实现的。不想累述。
3 ConcurrentHashMap
public class ConcurrentHashMap<K,V> extends AbstractMap<K,V>
implements ConcurrentMap<K,V>, Serializable {
类说明:
由hash表实现,支持并行和并发,和HashTable类似。它是如何做到。这要从属性和方法去分析。
它的很多都和HashMap类似。我们主要关注的是如何做到的支持并行并发的,以及多的属性和方法。
// 三个原子操作
// 获取tab数组的第i个node
static final <K,V> Node<K,V> tabAt(Node<K,V>[] tab, int i) {
return (Node<K,V>)U.getObjectVolatile(tab, ((long)i << ASHIFT) + ABASE);
}
// 利用CAS算法设置i位置上的node节点。
static final <K,V> boolean casTabAt(Node<K,V>[] tab, int i,
Node<K,V> c, Node<K,V> v) {
return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, v);
}
// 利用volatile方法设置第i个节点的值,
static final <K,V> void setTabAt(Node<K,V>[] tab, int i, Node<K,V> v) {
U.putObjectVolatile(tab, ((long)i << ASHIFT) + ABASE, v);
}
属性volatile:
/**
* volatile的桶数组
*/
transient volatile Node<K,V>[] table;
/**
* 非空调整大小时使用,volatile的桶数组
*/
private transient volatile Node<K,V>[] nextTable;
/**
* 基础计数器,主要无竞争时使用,它通过CAS更新
*/
private transient volatile long baseCount;
/**
* 表初始化和大小调整判断 -1:初始化,其他大小调整
*/
private transient volatile int sizeCtl;
/**
* 调整大小拆分的索引.
*/
private transient volatile int transferIndex;
/**
* 调整大小和创建CounterCells使用CAS锁
*/
private transient volatile int cellsBusy;
/**
* 计数器细胞表,大小始终为2的幂次方法
*/
private transient volatile CounterCell[] counterCells;
构造方法:
和HashMap中的构造方法基本一样,不累述。
put方法:
public V put(K key, V value) {
return putVal(key, value, false);
}
/** Implementation for put and putIfAbsent */
final V putVal(K key, V value, boolean onlyIfAbsent) {
// 这里可以看到key和value都不能为null
if (key == null || value == null) throw new NullPointerException();
int hash = spread(key.hashCode());
int binCount = 0;
for (Node<K,V>[] tab = table;;) {
Node<K,V> f; int n, i, fh;
// 没有,则初始化
if (tab == null || (n = tab.length) == 0)
tab = initTable();
// 查找hash对应没有值,加CAS锁并设值
else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
if (casTabAt(tab, i, null,
new Node<K,V>(hash, key, value, null)))
break; // no lock when adding to empty bin
}
else if ((fh = f.hash) == MOVED)
tab = helpTransfer(tab, f);
else {
V oldVal = null;
// 加synchronized 锁保证对树的操作
synchronized (f) {
if (tabAt(tab, i) == f) {
if (fh >= 0) {
binCount = 1;
for (Node<K,V> e = f;; ++binCount) {
K ek;
if (e.hash == hash &&
((ek = e.key) == key ||
(ek != null && key.equals(ek)))) {
oldVal = e.val;
if (!onlyIfAbsent)
e.val = value;
break;
}
Node<K,V> pred = e;
if ((e = e.next) == null) {
pred.next = new Node<K,V>(hash, key,
value, null);
break;
}
}
}
else if (f instanceof TreeBin) {
Node<K,V> p;
binCount = 2;
if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key,
value)) != null) {
oldVal = p.val;
if (!onlyIfAbsent)
p.val = value;
}
}
}
}
if (binCount != 0) {
if (binCount >= TREEIFY_THRESHOLD)
treeifyBin(tab, i);
if (oldVal != null)
return oldVal;
break;
}
}
}
addCount(1L, binCount);
return null;
}
get方法:
public V get(Object key) {
Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
int h = spread(key.hashCode());
if ((tab = table) != null && (n = tab.length) > 0 &&
(e = tabAt(tab, (n - 1) & h)) != null) {
if ((eh = e.hash) == h) {
if ((ek = e.key) == key || (ek != null && key.equals(ek)))
return e.val;
}
else if (eh < 0)
return (p = e.find(h, key)) != null ? p.val : null;
while ((e = e.next) != null) {
if (e.hash == h &&
((ek = e.key) == key || (ek != null && key.equals(ek))))
return e.val;
}
}
return null;
}
remove方法:
public V remove(Object key) {
return replaceNode(key, null, null);
}
/**
* synchronized 锁实现删除
*/
final V replaceNode(Object key, V value, Object cv) {
int hash = spread(key.hashCode());
for (Node<K,V>[] tab = table;;) {
Node<K,V> f; int n, i, fh;
if (tab == null || (n = tab.length) == 0 ||
(f = tabAt(tab, i = (n - 1) & hash)) == null)
break;
else if ((fh = f.hash) == MOVED)
tab = helpTransfer(tab, f);
else {
V oldVal = null;
boolean validated = false;
synchronized (f) {
if (tabAt(tab, i) == f) {
if (fh >= 0) {
validated = true;
for (Node<K,V> e = f, pred = null;;) {
K ek;
if (e.hash == hash &&
((ek = e.key) == key ||
(ek != null && key.equals(ek)))) {
V ev = e.val;
if (cv == null || cv == ev ||
(ev != null && cv.equals(ev))) {
oldVal = ev;
if (value != null)
e.val = value;
else if (pred != null)
pred.next = e.next;
else
setTabAt(tab, i, e.next);
}
break;
}
pred = e;
if ((e = e.next) == null)
break;
}
}
else if (f instanceof TreeBin) {
validated = true;
TreeBin<K,V> t = (TreeBin<K,V>)f;
TreeNode<K,V> r, p;
if ((r = t.root) != null &&
(p = r.findTreeNode(hash, key, null)) != null) {
V pv = p.val;
if (cv == null || cv == pv ||
(pv != null && cv.equals(pv))) {
oldVal = pv;
if (value != null)
p.val = value;
else if (t.removeTreeNode(p))
setTabAt(tab, i, untreeify(t.first));
}
}
}
}
}
if (validated) {
if (oldVal != null) {
if (value == null)
addCount(-1L, -1);
return oldVal;
}
break;
}
}
}
return null;
}
其他的方法都是在这上面的基础之上。想了解去看源码。这里不再大篇幅累述。
3 Stack和Vector
public
class Stack<E> extends Vector<E> {
它继承了Vector。所以Stack是线程安全的。虽说Stack和Vector已过时,不推荐使用。但是呢,该用还是一样的用。
它所维护的就是一个动态数组:(和List一样)
public
class Stack<E> extends Vector<E> {
/**
* 唯一构造器
*/
public Stack() {
}
/**
* push一个元素
*/
public E push(E item) {
addElement(item);
return item;
}
/**
* 移除一个元素,并返回该元素
*/
public synchronized E pop() {
E obj;
int len = size();
obj = peek();
removeElementAt(len - 1);
return obj;
}
/**
* 得到栈顶元素
*/
public synchronized E peek() {
int len = size();
if (len == 0)
throw new EmptyStackException();
return elementAt(len - 1);
}
/**
* Tests if this stack is empty.
*/
public boolean empty() {
return size() == 0;
}
/**
* 查找元素
*/
public synchronized int search(Object o) {
int i = lastIndexOf(o);
if (i >= 0) {
return size() - i;
}
return -1;
}
/** use serialVersionUID from JDK 1.0.2 for interoperability */
private static final long serialVersionUID = 1224463164541339165L;
}
来自父类的方法:
添加:
public synchronized void addElement(E obj) {
modCount++;
ensureCapacityHelper(elementCount + 1);
elementData[elementCount++] = obj;
}
删除:
public synchronized void removeElementAt(int index) {
modCount++;
if (index >= elementCount) {
throw new ArrayIndexOutOfBoundsException(index + " >= " +
elementCount);
}
else if (index < 0) {
throw new ArrayIndexOutOfBoundsException(index);
}
int j = elementCount - index - 1;
if (j > 0) {
System.arraycopy(elementData, index + 1, elementData, index, j);
}
elementCount--;
elementData[elementCount] = null; /* to let gc do its work */
}
4 queue
4.1 LinkedBlockingDeque
public class LinkedBlockingDeque<E>
extends AbstractQueue<E>
implements BlockingDeque<E>, java.io.Serializable {
这个queue是阻塞双端队列。
来看看构造器:
/**
* 创建初始容量int最大值的queue
*/
public LinkedBlockingDeque() {
this(Integer.MAX_VALUE);
}
/**
* 构造指定容量的LinkedBlockingDeque
*/
public LinkedBlockingDeque(int capacity) {
if (capacity <= 0) throw new IllegalArgumentException();
this.capacity = capacity;
}
/**
* 构造Collection下其他集合的转换
*/
public LinkedBlockingDeque(Collection<? extends E> c) {
this(Integer.MAX_VALUE);
// 加锁
final ReentrantLock lock = this.lock;
lock.lock(); // Never contended, but necessary for visibility
try {
for (E e : c) {
if (e == null)
throw new NullPointerException();
if (!linkLast(new Node<E>(e)))
throw new IllegalStateException("Deque full");
}
} finally {
lock.unlock();
}
}
来看看属性和维护的对象:
/** 静态双链表对象 */
static final class Node<E> {
// 值
E item;
// 上一个节点
Node<E> prev;
// 下一个节点
Node<E> next;
Node(E x) {
item = x;
}
}
/**
* 头节点
*/
transient Node<E> first;
/**
* 尾节点
*/
transient Node<E> last;
/** 双端队列中元素个数 */
private transient int count;
/** 最大容量 */
private final int capacity;
/** 主锁,保护所有通道 */
final ReentrantLock lock = new ReentrantLock();
/** 等待条件锁take */
private final Condition notEmpty = lock.newCondition();
/** 等待条件锁put */
private final Condition notFull = lock.newCondition();
从上面我们可以看出他所维护的就是这个双链表对象。
来看看它是如何维护这个对象的。
add方法:
public boolean add(E e) {
addLast(e);
return true;
}
public void addLast(E e) {
if (!offerLast(e))
throw new IllegalStateException("Deque full");
}
public boolean offerLast(E e) {
if (e == null) throw new NullPointerException();
Node<E> node = new Node<E>(e);
// 添加前加锁
final ReentrantLock lock = this.lock;
lock.lock();
try {
return linkLast(node);
} finally {
// 添加完释放锁
lock.unlock();
}
}
private boolean linkLast(Node<E> node) {
// assert lock.isHeldByCurrentThread();
if (count >= capacity)
return false;
// 添加到末尾,即是改变链表指向
Node<E> l = last;
node.prev = l;
last = node;
if (first == null)
first = node;
else
l.next = node;
++count;
// 消费者唤醒
notEmpty.signal();
return true;
}
上面的添加,除了添加加锁,都是很常规的链表操作。
element方法:获取第一个,但不删除
public E element() {
return getFirst();
}
public E getFirst() {
E x = peekFirst();
if (x == null) throw new NoSuchElementException();
return x;
}
public E peekFirst() {
final ReentrantLock lock = this.lock;
// 获取操作加锁
lock.lock();
try {
return (first == null) ? null : first.item;
} finally {
lock.unlock();
}
}
offer方法:
public boolean offer(E e) {
// 这里是不是和add对比少了一个异常呢
return offerLast(e);
}
public boolean offerLast(E e) {
if (e == null) throw new NullPointerException();
Node<E> node = new Node<E>(e);
final ReentrantLock lock = this.lock;
lock.lock();
try {
return linkLast(node);
} finally {
lock.unlock();
}
}
和add方法一对比,不是一样的逻辑嘛。仔细看就少了个异常。
因此:
Queue 中 add() 和 offer()都是用来向队列添加一个元素。
在容量已满的情况下,add() 方法会抛出IllegalStateException异常,offer() 方法只会返回 false 。
先入先出。我们来看看‘出’:
peek方法:只弹出,不删除。它和element差距弹出null不会报异常。
public E peek() {
return peekFirst();
}
public E peekFirst() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
return (first == null) ? null : first.item;
} finally {
lock.unlock();
}
}
pop方法:
public E pop() {
return removeFirst();
}
public E removeFirst() {
E x = pollFirst();
if (x == null) throw new NoSuchElementException();
return x;
}
public E pollFirst() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
return unlinkFirst();
} finally {
lock.unlock();
}
}
// 改变链表指向
private E unlinkFirst() {
// assert lock.isHeldByCurrentThread();
Node<E> f = first;
if (f == null)
return null;
Node<E> n = f.next;
E item = f.item;
f.item = null;
f.next = f; // help GC
first = n;
if (n == null)
last = null;
else
n.prev = null;
--count;
notFull.signal();
return item;
}
还可以移除指定对象:
public boolean remove(Object o) {
return removeFirstOccurrence(o);
}
public boolean removeFirstOccurrence(Object o) {
if (o == null) return false;
final ReentrantLock lock = this.lock;
lock.lock();
try {
for (Node<E> p = first; p != null; p = p.next) {
if (o.equals(p.item)) {
unlink(p);
return true;
}
}
return false;
} finally {
lock.unlock();
}
}
void unlink(Node<E> x) {
// assert lock.isHeldByCurrentThread();
Node<E> p = x.prev;
Node<E> n = x.next;
if (p == null) {
unlinkFirst();
} else if (n == null) {
unlinkLast();
} else {
p.next = n;
n.prev = p;
x.item = null;
// Don't mess with x's links. They may still be in use by
// an iterator.
--count;
notFull.signal();
}
}
除了上面来自queue的方法。由双链表的队列。有很多双向的操作。
比如:
addFirst、addLast、offerFirst、offerLast、removeFirst、removeLast、pollFirst、pollLast。都是对该队列头和尾操作。
关于queue这是项大工程:
分为实现了阻塞队列BlockingQueue 和没有实现阻塞队列BlockingQueue 两种:
Queue的实现
1、 PriorityQueue 有序优先列表
ConcurrentLinkedQueue 线程安全
2、 ArrayBlockingQueue :一个由数组支持的有界队列。
LinkedBlockingQueue :一个由链接节点支持的可选有界队列。(前面已讲)
PriorityBlockingQueue :一个由优先级堆支持的无界优先级队列。
DelayQueue :一个由优先级堆支持的、基于时间的调度队列。
SynchronousQueue :一个利用 BlockingQueue 接口的简单聚集(rendezvous)机制。
来看看无界队列PriorityBlockingQueue :
public class PriorityBlockingQueue<E> extends AbstractQueue<E>
implements BlockingQueue<E>, java.io.Serializable {
该类说明:
1、实现了阻塞队列。
2、无界,不可插入不可比较元素,不能为null。
看看属性:
/**
* 默认数组初始容量 11
*/
private static final int DEFAULT_INITIAL_CAPACITY = 11;
/**
* 为数组申请的最大大小。超过该值报错OutOfMemoryError
*/
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
/**
* 优先队列表示为平衡的二进制堆:两个子孩子queue[2*n+1] and queue[2*(n+1)]
* 有指定排序或者自然排序
*/
private transient Object[] queue;
/**
* 元素个数
*/
private transient int size;
/**
* 比较器
*/
private transient Comparator<? super E> comparator;
/**
* 公共加锁
*/
private final ReentrantLock lock;
/**
* 为空时条件阻塞
*/
private final Condition notEmpty;
/**
* 自旋锁进行分配,通过CAS获取。
*/
private transient volatile int allocationSpinLock;
/**
* 仅仅序列化考虑
*/
private PriorityQueue<E> q;
再看看构造方法:
// 构造初始容量11 ,自然排序
public PriorityBlockingQueue() {
this(DEFAULT_INITIAL_CAPACITY, null);
}
/**
* 构造指定容量,自然排序
*/
public PriorityBlockingQueue(int initialCapacity) {
this(initialCapacity, null);
}
/**
* 构造指定初始容量,指定排序
*/
public PriorityBlockingQueue(int initialCapacity,
Comparator<? super E> comparator) {
if (initialCapacity < 1)
throw new IllegalArgumentException();
this.lock = new ReentrantLock();
this.notEmpty = lock.newCondition();
this.comparator = comparator;
this.queue = new Object[initialCapacity];
}
/**
* Collection下其他的集合的转化
*/
public PriorityBlockingQueue(Collection<? extends E> c) {
this.lock = new ReentrantLock();
this.notEmpty = lock.newCondition();
boolean heapify = true; // true if not known to be in heap order
boolean screen = true; // true if must screen for nulls
if (c instanceof SortedSet<?>) {
SortedSet<? extends E> ss = (SortedSet<? extends E>) c;
this.comparator = (Comparator<? super E>) ss.comparator();
heapify = false;
}
else if (c instanceof PriorityBlockingQueue<?>) {
PriorityBlockingQueue<? extends E> pq =
(PriorityBlockingQueue<? extends E>) c;
this.comparator = (Comparator<? super E>) pq.comparator();
screen = false;
if (pq.getClass() == PriorityBlockingQueue.class) // exact match
heapify = false;
}
Object[] a = c.toArray();
int n = a.length;
// If c.toArray incorrectly doesn't return Object[], copy it.
if (a.getClass() != Object[].class)
a = Arrays.copyOf(a, n, Object[].class);
if (screen && (n == 1 || this.comparator != null)) {
for (int i = 0; i < n; ++i)
if (a[i] == null)
throw new NullPointerException();
}
this.queue = a;
this.size = n;
if (heapify)
heapify();
}
分析类这么多你会发现其他的queue,他也肯定是在维护某个对象。或数组或链表或树。
我就来看看分别维护的是什么。具体的操作方法,你用到时详细去了解。
PriorityQueue | transient Object[] queue; 数组 |
---|---|
ConcurrentLinkedQueue | Node 链表 |
ArrayBlockingQueue | final Object[] items;数组 |
DelayQueue | private final PriorityQueue q = new PriorityQueue(); 优先队列 |
SynchronousQueue | 还没看懂 |
上面的具体细节。这里我不讲了。之后会将多线程,并发并行一起拿出来分。其实之前已经在多线程中讲过上面的这些集合。但是都是从实际中应用,什么场景下用什么。没有分析源码,到底是怎么做到的。
详细参考:
并发容器