与JDK1.7相比,JDK1.8对集合做了很多优化,这些优化里有很多优秀的算法、思想等等值得学习,所以在这里一一列出,便以后回顾,也希望对读者有些帮助
我们可以从构造器、扩容机制、增删改查、迭代器、并发修改异常等各个方面来分析
Collection
List
ArrayList
LinkedList
VectoSet
HashSet
LinkedHashSet
TreeSetMap
HashMap
LinkedHashMap
TreeMap
HashTableProperties
构造器
扩容机制
增删改查方法
JDK1.7中
/**
* Constructs an empty list with an initial capacity of ten.
*/
public ArrayList() {
this(10);
}
JDK1.8中
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
/**
* Constructs an empty list with an initial capacity of ten.
*/
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
我们可以看出,在JDK1.7中无参构造器初始化时就实例化了一个长度为10的数组;
而在JDK1.8中,无参构造器值引用了一个全局静态的一个空数组;
这种改变有什么好处呢?
JDK1.7
/**
* Constructs an empty list with the specified initial capacity.
*
* @param initialCapacity the initial capacity of the list
* @throws IllegalArgumentException if the specified initial capacity
* is negative
*/
public ArrayList(int initialCapacity) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.elementData = new Object[initialCapacity];
}
JDK1.8
private static final Object[] EMPTY_ELEMENTDATA = {};
/**
* Constructs an empty list with the specified initial capacity.
*
* @param initialCapacity the initial capacity of the list
* @throws IllegalArgumentException if the specified initial capacity
* is negative
*/
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);
}
}
JDK1.8只是多出了一些条件判断,当初始化容量为0的时候,依然只引用了一个全局静态空数组,静态保证全局唯一,提高资源利用率
JDK1.7
/**
* Constructs a list containing the elements of the specified
* collection, in the order they are returned by the collection's
* iterator.
*
* @param c the collection whose elements are to be placed into this list
* @throws NullPointerException if the specified collection is null
*/
public ArrayList(Collection<? extends E> c) {
elementData = c.toArray();
size = elementData.length;
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
}
JDK1.8
/**
* Constructs a list containing the elements of the specified
* collection, in the order they are returned by the collection's
* iterator.
*
* @param c the collection whose elements are to be placed into this list
* @throws NullPointerException if the specified collection is null
*/
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;
}
}
public Object[] toArray() {
return Arrays.copyOf(elementData, size);
}
大家可以参考这一片博客来加以理解:集合源码中toArray方法的bug
首先,我们只有向ArrayList中添加数据的时候,才有可能引发扩容,所以我们从add方法入手分析:
/**
* Appends the specified element to the end of this list.
*
* @param e element to be appended to this list
* @return true (as specified by {@link Collection#add})
*/
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
ensureCapacityInternal:这个方法就是扩容机制对外暴露的接口,它隐藏了扩容的实现机制,我们无需知道扩容原理,就可直接实现扩容;
private void ensureCapacityInternal(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
modCount这个属性,是处理并发修改的重要属性,我们在分析迭代器的时候在仔细深究
在源码中,只要是minCapacity,我们都可以理解为是最小需求容量
/**
* Increases the capacity to ensure that it can hold at least the
* number of elements specified by the minimum capacity argument.
*
* @param minCapacity the desired minimum capacity
*/
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
// 扩容为原来的1.5倍
int newCapacity = oldCapacity + (oldCapacity >> 1);
// 如果我们扩容(1.5倍)之后的容量还小于最小需求容量,那么就直接把minCapacity作为容量
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);
}
无非就是一些条件过滤
public boolean add(E e) {
// 我们可以看到JDK1.8中扩容对外暴露的接口与JDK1.7相同
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
以下方法是计算需求容量(minCapacity)的,无非就是与默认容量10相比,minCapacity < 10 ? 10 :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);
}
至于JDK1.8的grow方法和JDK1.7完全一样
扩容机制带来的思想:
我们可以看到将扩容方法封装,对外暴露接口的好处:
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
public void add(int index, E element) {
//因为在类中多次出现这个代码,所以我们就封装了一个方法
rangeCheckForAdd(index);
ensureCapacityInternal(size + 1); // Increments modCount!!
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
elementData[index] = element;
size++;
}
以上两个添加单个元素的方法,无非就是确定容量、移动元素(数组拷贝),size++;判断下标
public boolean addAll(Collection<? extends E> c) {
// 这里我们注意到,它和我们之前构造器中说过toArray可能产生异常,为什么这个没有呢?
// 哈哈,那是因为我们这个方法的形参中使用上限通配符(?)规定了泛型的上限,所以方法内部不可能再产生类型转换错误等异常了
Object[] a = c.toArray();
int numNew = a.length;
ensureCapacityInternal(size + numNew); // Increments modCount
System.arraycopy(a, 0, elementData, size, numNew);
size += numNew;
return numNew != 0;
}
public boolean addAll(int index, Collection<? extends E> c) {
rangeCheckForAdd(index);
Object[] a = c.toArray();
int numNew = a.length;
ensureCapacityInternal(size + numNew); // Increments modCount
int numMoved = size - index;
if (numMoved > 0)
System.arraycopy(elementData, index, elementData, index + numNew,
numMoved);
System.arraycopy(a, 0, elementData, index, numNew);
size += numNew;
return numNew != 0;
}
在某个下标处添加、删除元素,无非就是死套路:
public boolean remove(Object o):删除第一次出现的元素
public boolean remove(Object o) {
//当我们传入的参数是引用类型的时候,都要考虑是否需要空值处理
if (o == null) {
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
fastRemove(index);
return true;
}
} else {
for (int index = 0; index < size; index++)
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
return false;
}
private void fastRemove(int index) {
modCount++;
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // clear to let GC do its work
}
public E remove(int index):删除指定位置的元素
public E remove(int index) {
rangeCheck(index);
modCount++;
E oldValue = elementData(index);
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // clear to let GC do its work
return oldValue;
}
public boolean removeAll(Collection c)
public boolean removeAll(Collection<?> c) {
//空值判断,抛空指针异常
Objects.requireNonNull(c);
//batch...: 批量操作,在jdbcTemplate中也有这种方法
return batchRemove(c, false);
}
// 这个batchRemove方法值得深究一下,removeAll和retainAll两个方法都调用了这个方法
// 我们先说removeAll调用这个方法的执行流程
// 1.首先removeAll中传入complement = false,这个是什么意思呢?在代码中会更好的体会
private boolean batchRemove(Collection<?> c, boolean complement) {
final Object[] elementData = this.elementData;
int r = 0, w = 0;
boolean modified = false;
try {
// 思路:
// 1.complement为false: 遍历elementData中的元素,判断在c集合中有没有
// 如果没有,就将其移至最前面,最后把后面的置null,这样就实现了删除c集合中的元素,
// 即将elementData中独有的元素移至前面保留下来
// 2.complement为true: 遍历elementData中的元素,判断在c集合中有没有
// 如果有,就将其移至前面,最后把后面的置null,这样就实现了交集的操作,
// 即将elementData中的在c中也有的保留下来(交集)
for (; r < size; r++)
if (c.contains(elementData[r]) == complement)
elementData[w++] = elementData[r];
} finally {
// Preserve behavioral compatibility with AbstractCollection,
// even if c.contains() throws.
//上面的翻译:保证与 AbstractCollection 的兼容,防止c.contains抛异常
if (r != size) {
System.arraycopy(elementData, r,
elementData, w,
size - r);
w += size - r;
}
if (w != size) {
// clear to let GC do its work
for (int i = w; i < size; i++)
elementData[i] = null;
modCount += size - w;
size = w;
modified = true;
}
}
return modified;
}
protected void removeRange(int fromIndex, int toIndex):
protected void removeRange(int fromIndex, int toIndex) {
modCount++;
int numMoved = size - toIndex;
System.arraycopy(elementData, toIndex, elementData, fromIndex,
numMoved);
// clear to let GC do its work
int newSize = size - (toIndex-fromIndex);
for (int i = newSize; i < size; i++) {
elementData[i] = null;
}
size = newSize;
}
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
public E set(int index, E element) {
rangeCheck(index);
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
作用:将elementData数组的大小缩小为size;
/**
* Trims the capacity of this ArrayList instance to be the
* list's current size. An application can use this operation to minimize
* the storage of an ArrayList instance.
*/
public void trimToSize() {
modCount++;
if (size < elementData.length) {
elementData = (size == 0)
? EMPTY_ELEMENTDATA
: Arrays.copyOf(elementData, size);
}
}
public boolean retainAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, true);
}
// 这个batchRemove方法值得深究一下,removeAll和retainAll两个方法都调用了这个方法
// 我们先说removeAll调用这个方法的执行流程
// 1.首先removeAll中传入complement = false,这个是什么意思呢?在代码中会更好的体会
private boolean batchRemove(Collection<?> c, boolean complement) {
final Object[] elementData = this.elementData;
int r = 0, w = 0;
boolean modified = false;
try {
// 思路:
// 1.complement为false: 遍历elementData中的元素,判断在c集合中有没有
// 如果没有,就将其移至最前面,最后把后面的置null,这样就实现了删除c集合中的元素,
// 即将elementData中独有的元素移至前面保留下来
// 2.complement为true: 遍历elementData中的元素,判断在c集合中有没有
// 如果有,就将其移至前面,最后把后面的置null,这样就实现了交集的操作,
// 即将elementData中的在c中也有的保留下来(交集)
for (; r < size; r++)
if (c.contains(elementData[r]) == complement)
elementData[w++] = elementData[r];
} finally {
// Preserve behavioral compatibility with AbstractCollection,
// even if c.contains() throws.
//上面的翻译:保证与 AbstractCollection 的兼容,防止c.contains抛异常
if (r != size) {
System.arraycopy(elementData, r,
elementData, w,
size - r);
w += size - r;
}
if (w != size) {
// clear to let GC do its work
for (int i = w; i < size; i++)
elementData[i] = null;
modCount += size - w;
size = w;
modified = true;
}
}
return modified;
}