特点:有序、可重复、查找快、插入和删除慢、线程不安全
private static final int DEFAULT_CAPACITY = 10;
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
private static final Object[] EMPTY_ELEMENTDATA = {};
transient Object[] elementData;
private int size;
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_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);
}
}
代码中可以看到,在无参的ArrayList里,会使用DEFAULT_CAPACITY = 10来规定容量,而拥有两个empty_elementdata的原因是用于区分list在空的时候使用默认容量还是自定义容量,使用static final修饰是为了保证多个空list共享同一个空数组,否则多个空list需要新建多个空数组浪费空间。
真正存放数据的是数组elementdata,所以arraylist的底层由数组来实现,transient用于在序列化时,不对elementdata进行序列化,原因是因为arraylist容器的容量往往是大于数据实际的规模的,从而有很多空的空间,为节省空间等目的,arraylist自身重写了writeobject和readobject来确保空的数据不会被保存进序列化文件。
以下是一个不常用的用集合来初始化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;
}
}
利用toarray试图将改集合转化为数组,size代表集合的大小,通过别的集合来构造arraylist的时候需要赋值size,下面的class判断是为了放置toarray出错,没有转为数组,就用copyof把元素复制到数组中去,如果c没有元素,就把EMPTY_ELEMENTDATA赋值给elementdata。
toarray的作用是把集合中的元素全部赋值给数组,而copyof则根据class类型来决定new还是反射来创建对象,以下是copyof的源码:
public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
@SuppressWarnings("unchecked")
T[] copy = ((Object)newType == (Object)Object[].class)
? (T[]) new Object[newLength]
: (T[]) Array.newInstance(newType.getComponentType(), newLength);
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
return copy;
}
System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length)的作用:将数组src从下标为srcPos开始拷贝,一直拷贝length个元素到dest数组中,在dest数组中从destPos开始加入scrPos数组元素。
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
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);
}
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;
}
Integer. MAX_VALUE = 0x7fffffff;
MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8
modcount就是用于记录arraylist一共修改过几次,查和改不会改变改值。
第一种就是在尾部插入一个element,但复杂的是在插入之后要进行容器扩容的判断,首先确定容器是否是默认容量的空容器,如果是就把新的size和默认大小取大值,再进行确定新的size是否超过了原来数组的大小,如果超过了,就说明要进行扩容,从而调用grow方法,默认进行1.5倍的扩容,如果进行了扩容依然小于最小容量,那么就扩容至最小容量,并且还要判定最小容量是否超过了arraylist的最大容量,如果超过,那么只能取最大容量,再用copyof把元素进行复制,最后返回到add方法添加新的元素。
public void add(int index, E element) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException(outOfBoundsMsg(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) {
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;
}
最后一种是批量加入数据,实际上和插入单个数据很相似,确认容量之后把所有元素批量复制到arraylist的尾部,
更新size
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
}
删除的方法比较简单,但是由于同样涉及到元素的移动,性能比较差。
首先从头开始遍历数组直到找到第一个符合的元素并删除,最后把元素后面的所有元素前移,更新size,并不再强引用最后空出来的尾部数据,让GC处理。
public E remove(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
modCount++;
E oldValue = (E) 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) {
Objects.requireNonNull(c);
return batchRemove(c, false);
}
public static <T> T requireNonNull(T obj) {
if (obj == null)
throw new NullPointerException();
return obj;
}
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;
}
批量删除更加复杂一些,首先确保传进来的元素集合并不为空,接着elementdata重新指向成员变量elementdata存储最终过滤后的元素,从头遍历把所有c集合中不包含的元素存储到最终的数组。
finally代码块的用处是如果发生异常,保证数据不会丢失,如果r!=size说明数组没有完全遍历,就把没有遍历部分的元素都拷贝到最终数组的尾部,如果w!=size,说明有元素被提出了,就要把空的位置的强引用取消,让gc进行回收并且更新size,同时要注意的是modcount并不只增加了一,而是增加了删除的元素个数。
public E set(int index, E element) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
E oldValue = (E) elementData[index];
elementData[index] = element;
return oldValue;
}
数组的修改十分简单,只要确保下标没有越界,就更改下标的数据并且返回原来的数据
public E get(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
return (E) elementData[index];
}
数组的查询也很简单,只要下标没有越界,返回数据即可。
public void clear() {
modCount++;
// clear to let GC do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
清空也很简单,让所有元素都取消强引用,更新size为0即可
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
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;
}
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;
}
contains方法从头遍历,lastindexof从尾部遍历
public Iterator<E> iterator() {
return new Itr();
}
private class Itr implements Iterator<E> {
// Android-changed: Add "limit" field to detect end of iteration.
// The "limit" of this iterator. This is the size of the list at the time the
// iterator was created. Adding & removing elements will invalidate the iteration
// anyway (and cause next() to throw) so saving this value will guarantee that the
// value of hasNext() remains stable and won't flap between true and false when elements
// are added and removed from the list.
protected int limit = ArrayList.this.size;
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount;
public boolean hasNext() {
return cursor < limit;
}
@SuppressWarnings("unchecked")
public E next() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
int i = cursor;
if (i >= limit)
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();
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
limit--;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
该方法返回集合的迭代器,limit用来记录当前集合的大小,cursor游标记录下个元素的下标,lastret记录上个返回元素的下标,hasNext通过判断cursor和limit的大小判断是否还有下个元素,下面的next和remove进行了很多异步线程的检查。
首先有一个expectmodcount记录在调用迭代器的时候arraylist更改的次数,然后在对arraylist进行更改的时候会进行比较,如果当前的modcount和expectedmodcount不相等,说明有另一个线程更改了arraylist,那么再进行更改会发生不可预计的错误,所以这里扔出一个异常,然后检查cursor是否超过了limit,如果超过就没有下一个元素了,也扔出一个异常,接下来用elementdata重新指向成员变量elementdata并检查i是否超过当前elementdata的长度,因为上方已经判断i是小于limit的,如果这里大于长度,说明当前的elementdata已经被其他线程删除了数据,就扔出一个异常,通过所有的检查则返回下一个元素。
remove先检查lastret是否为负数,是负数说明没有取过值那么自然没有值可以用来删除,同时检查modcount和expectedmodcount是否相等,不然抛出异常,最后删除元素并更新相关的数值,如果发现下标越界,说明有其他线程删除了元素,抛出异常。
以下是开头就说过的arraylist对序列化方法的重写。
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();
}
}
/**
* Reconstitute the ArrayList instance from a stream (that is,
* deserialize it).
*/
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();
}
}
}
学习自:https://www.cnblogs.com/wjtaigwh/p/9856951.html