List---ArrayList
概述
Resizable-array implementation of the <tt>List</tt> interface. Implements all optional list operations, and permits all elements, including <tt>null</tt>.
In addition to implementing the <tt>List</tt> interface, this class provides methods to manipulate the size of the array that is used internally to store the list.
可变大小数组 的List实现;
The <tt>size</tt>, <tt>isEmpty</tt>, <tt>get</tt>, <tt>set</tt>, <tt>iterator</tt>, and <tt>listIterator</tt> operations run in constant time.
The <tt>add</tt> operation runs in <i>amortized constant time</i>, that is, adding n elements requires O(n) time.
All of the other operations run in linear time (roughly speaking).
The constant factor is low compared to that for the <tt>LinkedList</tt> implementation.
size、isEmpty、get、Set、iterator以常量时间运行;
add操作需要O(n);
Each <tt>ArrayList</tt> instance has a <i>capacity</i>.
The capacity is the size of the array used to store the elements in the list.
It is always at least as large as the list size.
As elements are added to an ArrayList, its capacity grows automatically.
每个ArrayList都有一个capacity;
元素被add到ArrayList,ArrayList的capacity会自动增长;
An application can increase the capacity of an<tt>ArrayList</tt> instance before adding a large number of elements using the <tt>ensureCapacity</tt> operation.
在添加大数量的元素前,会使用ensureCapacity确保ArrayList容量;
Note that this implementation is not synchronized.
ArrayList的实现是非同步的;
If multiple threads access an <tt>ArrayList</tt> instance concurrently, and at least one of the threads modifies the list structurally, it <i>must</i> be synchronized externally.
如果多个线程并发访问ArrayList,必须在外部进行同步;
A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification.
结构修改:添加、删除元素、数组重置大小; (多于多线程并发 需要进行同步操作)
If no such object exists, the list should be "wrapped" using the {@link Collections#synchronizedList Collections.synchronizedList} method.
可以使用 Collections.synchronizedList 实现同步;
The iterators returned by this class's {@link #iterator() iterator} and {@link #listIterator(int) listIterator} methods are <em>fail-fast</em>:
iterator、listIterator 方法是fail-fast;
if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own {@link ListIterator#remove() remove}
or {@linkListIterator#add(Object) add} methods, the iterator will throw a {@link ConcurrentModificationException}.
如果创建了iterator,调用iterator的remove、add将会抛出ConcurrentModificationException(实际用的是子类的java.util.ArrayList.Itr)
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable{ private class Itr implements Iterator<E> { } private class ListItr extends Itr implements ListIterator<E> { } transient Object[] elementData; /** * Default initial capacity. */ private static final int DEFAULT_CAPACITY = 10; private static final Object[] EMPTY_ELEMENTDATA = {}; private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {}; }
链路
new ArrayList<>()
// java.util.ArrayList.ArrayList() public ArrayList() { this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; }
new ArrayList<>(10)
// java.util.ArrayList.ArrayList(int) 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); } }
a.get(0)
// java.util.ArrayList.get public E get(int index) { rangeCheck(index); return elementData(index); } // java.util.ArrayList.elementData E elementData(int index) { return (E) elementData[index]; // 从数组中按索引取 }
remove
// java.util.ArrayList.remove(int) 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; }
add
// java.util.ArrayList.add(E) public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!! elementData[size++] = e; return true; } // java.util.ArrayList.ensureCapacityInternal private void ensureCapacityInternal(int minCapacity) { ensureExplicitCapacity(calculateCapacity(elementData, minCapacity)); } // java.util.ArrayList.calculateCapacity private static int calculateCapacity(Object[] elementData, int minCapacity) { if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { return Math.max(DEFAULT_CAPACITY, minCapacity); } return minCapacity; } // java.util.ArrayList.ensureExplicitCapacity private void ensureExplicitCapacity(int minCapacity) { modCount++; // modCount递增 // overflow-conscious code if (minCapacity - elementData.length > 0) // 容量不足,扩容 grow(minCapacity); } // java.util.ArrayList.grow private void grow(int minCapacity) { // overflow-conscious code int oldCapacity = elementData.length; int newCapacity = oldCapacity + (oldCapacity >> 1); // 新容量 = 旧容量 + 旧容量/2 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); // 将元素旧数据 copy到 新数组中 }
list.iterator()
// java.util.ArrayList.iterator public Iterator<E> iterator() { return new Itr(); } // java.util.ArrayList.Itr private class Itr implements Iterator<E> { public boolean hasNext() { return cursor != size; } @SuppressWarnings("unchecked") public E next() { checkForComodification(); int i = cursor; if (i >= size) throw new NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) throw new ConcurrentModificationException(); cursor = i + 1; return (E) elementData[lastRet = i]; } public void remove() { if (lastRet < 0) throw new IllegalStateException(); checkForComodification(); try { ArrayList.this.remove(lastRet); cursor = lastRet; lastRet = -1; expectedModCount = modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } }
iterator.remove()
// java.util.ArrayList.Itr.remove public void remove() { if (lastRet < 0) throw new IllegalStateException(); checkForComodification(); try { ArrayList.this.remove(lastRet); cursor = lastRet; lastRet = -1; expectedModCount = modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } // java.util.ArrayList.remove(int) 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; }
每次remove,都要将数组重新copy一次;
a.removeAll(b)
集合a 与 集合b 的差集
// java.util.ArrayList.removeAll public boolean removeAll(Collection<?> c) { Objects.requireNonNull(c); return batchRemove(c, false); } // java.util.ArrayList.batchRemove 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) // contains比较2个元素是否相等 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; }
a.retainAll()
// java.util.ArrayList.retainAll public boolean retainAll(Collection<?> c) { Objects.requireNonNull(c); return batchRemove(c, true); } // java.util.ArrayList.batchRemove 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) // 使用contains比较2个元素是否相等 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; }
a.contains()
// java.util.ArrayList.contains public boolean contains(Object o) { return indexOf(o) >= 0; } // java.util.ArrayList.indexOf 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])) // 使用equals方法比较2个元素是否相等 return i; } return -1; }
Collections同步链路
List<String> synchronizedList = Collections.synchronizedList(list); synchronizedList.add("aaa"); Iterator<String> iterator1 = synchronizedList.iterator();
Collections.synchronizedList(list)
// java.util.Collections.synchronizedList(java.util.List<T>) public static <T> List<T> synchronizedList(List<T> list) { return (list instanceof RandomAccess ? new SynchronizedRandomAccessList<>(list) : new SynchronizedList<>(list)); } public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable { }
public class Collections { static class SynchronizedCollection<E> implements Collection<E>, Serializable { final Collection<E> c; // Backing Collection final Object mutex; // Object on which to synchronize SynchronizedCollection(Collection<E> c) { this.c = Objects.requireNonNull(c); mutex = this; } public Iterator<E> iterator() { return c.iterator(); // Must be manually synched by user! } public boolean add(E e) { synchronized (mutex) {return c.add(e);} } public boolean remove(Object o) { synchronized (mutex) {return c.remove(o);} } } static class SynchronizedList<E> extends SynchronizedCollection<E> implements List<E> { final List<E> list; SynchronizedList(List<E> list) { super(list); this.list = list; } public E get(int index) { synchronized (mutex) {return list.get(index);} } public E set(int index, E element) { synchronized (mutex) {return list.set(index, element);} } public void add(int index, E element) { synchronized (mutex) {list.add(index, element);} } public E remove(int index) { synchronized (mutex) {return list.remove(index);} } } static class SynchronizedRandomAccessList<E> extends SynchronizedList<E> implements RandomAccess { SynchronizedRandomAccessList(List<E> list) { super(list); } } }
add(E e)
// java.util.Collections.synchronizedList(java.util.List<T>) public static <T> List<T> synchronizedList(List<T> list) { return (list instanceof RandomAccess ? new SynchronizedRandomAccessList<>(list) : // ArrayList实现了RandomAccess new SynchronizedList<>(list)); } // java.util.Collections.SynchronizedRandomAccessList.SynchronizedRandomAccessList(java.util.List<E>) SynchronizedRandomAccessList(List<E> list) { super(list); } // java.util.Collections.SynchronizedList.SynchronizedList(java.util.List<E>) SynchronizedList(List<E> list) { super(list); this.list = list; } // java.util.Collections.SynchronizedCollection.add // SynchronizedRandomAccessList继承了SynchronizedList,SynchronizedList继承了SynchronizedCollection,调用的是SynchronizedCollection的add public boolean add(E e) { synchronized (mutex) {return c.add(e);} }