ArrayList-JDK1.8
0. 参考资料
1. 成员变量
private int size 实际元素个数
transient Object[] elementData
- transient 关键字,标识后,序列化时不会序列化该属性
- 实现原理:java的serialization把对象状态存储到硬盘,需要的时候读取出来使用。当我们不希望某字段,如密码,卡号等在网络上传输,transient把字段的生命周期仅存于调用者的内存中,而不会被持久化到磁盘。
- 被transient修饰的变量也能被序列化。序列化有实现Serializable接口,实现Exteranlizable接口两种方式。第二种方式需要重写writeExternal和readExternal方法,可以决定哪些属性需要序列化(包括被transient修饰的),且效率更高。但是对大量对象、重复对象则效率低。
- 静态变量不能被序列化。静态变量存在于全局区,而序列化是写到磁盘上面的,当我们获取该变量,JVM会去全局区查找,而不是磁盘。(参考原理,静态变量的生命周期也在内存中。)
用于构造函数的
/**
* Shared empty array instance used for empty instances.
*/
private static final Object[] EMPTY_ELEMENTDATA = {};
/**
* Shared empty array instance used for default sized empty instances. We
* distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
* first element is added.
*/
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
2. 构造函数
/**
* 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);
}
}
/**
* Constructs an empty list with an initial capacity of ten.
*/
public ArrayList() {
this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
}
构造函数size为空的情况下,只构建了一个空的数组。所谓的默认初始扩容为10,其实是在第一次add时扩容的。
/**
* 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;
}
}
将集合c转为数组,赋值非elementData。
如果数组为空,赋EMPTY_ELEMENTDATA;如果不为空,判断是否为Object类型,如果不是要转化为Object。
3. add方法
/**
* Appends the specified element to the end of this list.
*
* @param e element to be appended to this list
* @return <tt>true</tt> (as specified by {@link Collection#add})
*/
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 void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(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;
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);
}
扩容的方法如上。oldCapacity>>1是做了一个位移的操作,相当于除以二,也就是扩容了原来的1.5倍。扩容后,如果容量比最小需要的容量还小的话,就将需要的容量作为新容量扩容(扩容后太小的情况);如果容量比数组能扩容的最大容量还要大,那么使用hugeCapacity方法,判断是否内存溢出抛异常(扩容后太大的情况)。如果没有异常,有两种情况,需要容量比数组最大容量大的,返回Integer能存的最大值;否则返回数组最大值。
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
add(index,element)的情况
这种情况下,除了add操作,还会将目标位置的元素后移,给新元素腾出一个位置,然后再赋值。
如果index为最后一位,相当于没有后移。
/**
* Inserts the specified element at the specified position in this
* list. Shifts the element currently at that position (if any) and
* any subsequent elements to the right (adds one to their indices).
*
* @param index index at which the specified element is to be inserted
* @param element element to be inserted
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
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++;
}
4. remove方法
/**
* Removes the element at the specified position in this list.
* Shifts any subsequent elements to the left (subtracts one from their
* indices).
*
* @param index the index of the element to be removed
* @return the element that was removed from the list
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
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;
}
首先会检查index是否合法,如果合法,使用arraycopy直接覆盖掉要remove的那个元素。这个时候可能是前移了一位,所以对最后一个元素,即size所指向的元素,是重复的,使用
elementData[--size] = null 将冗余的元素回收。(为什么是--size不是size--,因为最后一位下标应该是size-1)
5. get 方法
/**
* Returns the element at the specified position in this list.
*
* @param index index of the element to return
* @return the element at the specified position in this list
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E get(int index) {
rangeCheck(index);
return elementData(index);
}
直接get即可