JDK中util包的ArrayList的源代码学习
ArrayList的介绍
ArrayList是List接口的可调整大小的数组实现。实现了所有的可选的列表的操作,并且允许包括null的所有元素。除了实现了List接口,ArrayList还提供了一些方法来操纵内部用于存储列表的数组的大小。(ArrayList大致相当于Vector,但是他是unsynchronized)
每一个ArrayList都有一个capacity(容量),容量为用于存储列表中元素的数组的大小。它总是至少和列表大小一样大。当元素添加到ArrayList时,它的容量会自动增长。
在使用ensureCapacity方法添加大量元素之前,可以先增加ArrayList的容量。这可能会减少增量重新分配的数量。
Note that this implementation is not synchronized.
如果多个线程同时访问一个ArrayList实例,并且至少有一个线程在结构上修改了list,则必须在外部对其进行同步。(结构修改是值添加或删除一个或多个元素的任何操作,或显式调整支持数组的大小;仅仅设置一个元素的值不是结构修改)这通常是通过在自然封装列表的某个对象上进行同步来完成的。如果不存在这样的对象,可以使用Collections.synchronizedList方法来包装list。最好在创建时执行此操作,以防止对列表的意外非同步访问。
List list = Collections.synchronizedList(new ArrayList(...))
ArrayList的 iterator 和 listIterator 方法返回的Iterator是fail-fast(快速故障):如果在Iterator创建之后的任何时候,以任何方式(除了通过Iterator自己的remove或add方法之外)对list进行结构修改,Iterator将抛出ConcurrentModificationException。因此,在面对并发修改时,Iterator会快速干净地失败,而不是冒着在将来不确定的时间出现任意的、不确定的行为的风险。
注意,不能保证迭代器的快速故障行为,因为一般来说,在存在非同步并发修改的情况下,不可能做出任何硬保证。fail-fast Iterators会尽最大努力抛出ConcurrentModificationException。因此,编写一个依赖于此异常来保证其正确性的程序是错误的:迭代器的fail-fast行为应该只用于检测bug。
ArrayList的类信息
ArrayList继承AbstractList类,实现List接口;而List接口则继承了Collection接口
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
public interface List<E> extends Collection<E>
ArrayList的字段信息
private static final int DEFAULT_CAPACITY = 10;
ArrayList的构造器
ArrayList的方法
grow()方法:增加list的capacity
/**
* 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;
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);
}
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
grow方法是可能内存溢出的;
如果oldCapacity足够大的话,newCapacity就会溢出变成负值,而minCapacity至少比oldCapacity大,newCapacity - minCapacity就会大于0,这样newCapacity的值就会是Integer.MAX_VALUE或者MAX_ARRAY_SIZE;
如果oldCapacity为0,minCapacity为Integer.MAX_VALUE,这样的话就使得内存溢出了。
ensureCapacity()方法:确保list可以容纳参数指定的元素数
/**
* Increases the capacity of this <tt>ArrayList</tt> instance, if
* necessary, to ensure that it can hold at least the number of elements
* specified by the minimum capacity argument.
*
* @param minCapacity the desired minimum capacity
*/
public void ensureCapacity(int minCapacity) {
int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
// any size if not default element table
? 0
// larger than default for default empty table. It's already
// supposed to be at default size.
: DEFAULT_CAPACITY;
if (minCapacity > minExpand) {
ensureExplicitCapacity(minCapacity);
}
}
private void ensureCapacityInternal(int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
}
ensureExplicitCapacity(minCapacity);
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
ensureCapacity方法确保了传入下一个方法的minCapacity参数是正数,ensureExplicitCapacity方法确保了传入下一个方法的minCapacity方法是大于elemenData.length的正数
indexOf()方法:得到传入参数在list中的下标
/**
* Returns the index of the first occurrence of the specified element
* in this list, or -1 if this list does not contain the element.
* More formally, returns the lowest index <tt>i</tt> such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
* or -1 if there is no such index.
*/
public int indexOf(Object o) {
if (o == null) {
for (int i = 0; i < size; i++)
if (elementData[i]==null)
return i;
} else {
for (int i = 0; i < size; i++)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
/**
* Returns the index of the last occurrence of the specified element
* in this list, or -1 if this list does not contain the element.
* More formally, returns the highest index <tt>i</tt> such that
* <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
* or -1 if there is no such index.
*/
public int lastIndexOf(Object o) {
if (o == null) {
for (int i = size-1; i >= 0; i--)
if (elementData[i]==null)
return i;
} else {
for (int i = size-1; i >= 0; i--)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
indexOf返回此列表中指定元素第一次出现的索引,如果此列表不包含该元素,则返回-1;
lastIndexOf返回此列表中指定元素最后一次出现的索引,如果此列表不包含该元素,则返回-1。
toArray()方法:list转换成array
public Object[] toArray() {
return Arrays.copyOf(elementData, size);
}
public <T> T[] toArray(T[] a) {
if (a.length < size)
// Make a new array of a's runtime type, but my contents:
return (T[]) Arrays.copyOf(elementData, size, a.getClass());
System.arraycopy(elementData, 0, a, 0, size);
if (a.length > size)
a[size] = null;
return a;
}
Object[] toArray():将会返回一个全新的Object[];
<T> T[] toArray(T[] a): 将会返回一个T[],如果已经存在,T.length < list.size()的时候,T[]将会是list转换为T[]之后的新数组;如果T.length > list.size()的时候,T[]中紧跟list结束之后的第一个元素将被设置成null(有助于确定list的长度,这个只有在调用者知道list中不包含任何空元素的时候)
E get(int index)、E set(int index, E element)、boolean add(E e)、add(int index, E element)、E remove(int index)、boolean remove(Object o)、clear()
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;
}
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++;
}
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 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;
}
public void clear() {
modCount++;
// clear to let GC do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
ArrayList的基础方法
addAll()方法
public boolean addAll(Collection<? extends E> c) {
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;
}
addAll分为有下标添加和无下标添加
removeRange()方法:
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;
}
从此列表中删除其索引介于fromIndex(包含)和toIndex(不包含)之间的所有元素。
removeAll()、retainAll()方法
public boolean removeAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, false);
}
public boolean retainAll(Collection<?> c) {
Objects.requireNonNull(c);
return batchRemove(c, true);
}
private boolean batchRemove(Collection<?> c, boolean complement) {
final Object[] elementData = this.elementData;
int r = 0, w = 0;
boolean modified = false;
try {
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.
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;
}
批量删除和保留参数中的所有元素
writeObject()、readObject()方法:序列化方法
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException{
// Write out element count, and any hidden stuff
int expectedModCount = modCount;
s.defaultWriteObject();
// Write out size as capacity for behavioural compatibility with clone()
s.writeInt(size);
// Write out all elements in the proper order.
for (int i=0; i<size; i++) {
s.writeObject(elementData[i]);
}
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
}
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
elementData = EMPTY_ELEMENTDATA;
// Read in size, and any hidden stuff
s.defaultReadObject();
// Read in capacity
s.readInt(); // ignored
if (size > 0) {
// be like clone(), allocate array based upon size not capacity
ensureCapacityInternal(size);
Object[] a = elementData;
// Read in all elements in the proper order.
for (int i=0; i<size; i++) {
a[i] = s.readObject();
}
}
}
transient Object[] elementData; element的修饰符是transient,序列化ArrayList需要手动写入
还有未列出来的获取Iterator的方法和subList的方法,都是属于内部私有类,代码太多有兴趣的可以去看看源码
forEach()方法:
@Override
public void forEach(Consumer<? super E> action) {
Objects.requireNonNull(action);
final int expectedModCount = modCount;
@SuppressWarnings("unchecked")
final E[] elementData = (E[]) this.elementData;
final int size = this.size;
for (int i=0; modCount == expectedModCount && i < size; i++) {
action.accept(elementData[i]);
}
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
}
JDK8的新方法,可以有限的优化代码
常用写法
for (String str : list){
System.out.println(str);
}
forEach写法
list.forEach(str-> System.out.println(str));
removeIf()方法:根据条件remove
public boolean removeIf(Predicate<? super E> filter) {
Objects.requireNonNull(filter);
// figure out which elements are to be removed
// any exception thrown from the filter predicate at this stage
// will leave the collection unmodified
int removeCount = 0;
final BitSet removeSet = new BitSet(size);
final int expectedModCount = modCount;
final int size = this.size;
for (int i=0; modCount == expectedModCount && i < size; i++) {
@SuppressWarnings("unchecked")
final E element = (E) elementData[i];
if (filter.test(element)) {
removeSet.set(i);
removeCount++;
}
}
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
// shift surviving elements left over the spaces left by removed elements
final boolean anyToRemove = removeCount > 0;
if (anyToRemove) {
final int newSize = size - removeCount;
for (int i=0, j=0; (i < size) && (j < newSize); i++, j++) {
i = removeSet.nextClearBit(i);
elementData[j] = elementData[i];
}
for (int k=newSize; k < size; k++) {
elementData[k] = null; // Let gc do its work
}
this.size = newSize;
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
modCount++;
}
return anyToRemove;
}
在JDK1.8中,Collection以及其子类新加入了removeIf方法,作用是按照一定规则过滤集合中的元素。例如:
idList.removeIf(id -> id == nul);
repalceAll()方法:根据条件replace
public void replaceAll(UnaryOperator<E> operator) {
Objects.requireNonNull(operator);
final int expectedModCount = modCount;
final int size = this.size;
for (int i=0; modCount == expectedModCount && i < size; i++) {
elementData[i] = operator.apply((E) elementData[i]);
}
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
modCount++;
}
operator -应用于每个元素的操作
将ArrayList中的所有元素替换为指定的元素。replaceAll()方法不返回任何值。 而是用operator的值替换arraylist的所有值。例如:
所有list元素转换为大写
list.replaceAll(e -> e.toUpperCase());
符合条件的的list元素转换
list.replaceAll(e -> e.equals(b)?c:e);
文章仅作为个人学习整理~