ArrayList是开发常用的有序集合,底层为动态数组实现。可以插入null,并允许重复。
下面是源码中一些比较重要属性:
1、ArrayList默认大小10。
/**
* Default initial capacity.
*/
private static final int DEFAULT_CAPACITY = 10;
2、elementData就是真正存放数据的数组。elementData[]本身是动态的,并不是数组的全部空间都会使用,所以加上transient关键词进行修饰,防止自动序列化。
transient Object[] elementData; // non-private to simplify nested class access
3、ArrayList的实际大小。每次进行add或者remove后,都会进行跟踪修订。
/**
* The size of the ArrayList (the number of elements it contains).
*
* @serial
*/
private int size;
下面分析主要方法:
1、add()方法有两个实现,一种是直接添加,一种是指定index添加。
直接添加代码如下:
/**
* 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;
}
- 扩容判断
- 元素插入elementData[]尾部,size加1
指定index添加方式:
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,判断指定索引是否合理
- 扩容判断
- 将原数组中从index往后的全部元素copy到index+1之后的位置。也就是把后续元素的索引全部+1
- 需插入的元素放入指定index
- size加1
add()方法中,数组扩容调用的最终方法如下:
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);
}
代码中看得出,ArrayList会在原先容量的基础上,扩容为原来的1.5倍(oldCapacity + (oldCapacity >> 1)),最大容量为Integer.MAX_VALUE。elementData也就是一个数组复制的过程了。所以在平常的开发中,实例化ArrayList时,可以尽量指定容量大小,减少扩容带来的数组复制开销。
2、remove()方法和add()类似,这里就只简单看下:
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后,用数组复制的方式进行元素的覆盖。最后一个elementData数组的元素就是成了垃圾数据,让GC进行回收。size减1。
3、序列化
/**
* Save the state of the <tt>ArrayList</tt> instance to a stream (that
* is, serialize it).
*
* @serialData The length of the array backing the <tt>ArrayList</tt>
* instance is emitted (int), followed by all of its elements
* (each an <tt>Object</tt>) in the proper order.
*/
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 <tt>ArrayList</tt> 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
int capacity = calculateCapacity(elementData, size);
SharedSecrets.getJavaOISAccess().checkArray(s, Object[].class, 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();
}
}
}
ArrayList是用动态数组elementData进行数据存储的,所以本身自定义了序列化与反序列化方法。当对象中自定义了 writeObject 和 readObject 方法时,JVM 会调用这两个自定义方法来实现序列化与反序列化。ArrayList只序列化elementData里面的数据。
来源:oschina
链接:https://my.oschina.net/u/4326386/blog/3673974