ArrayList 类
List接口下的实现类, 代表长度可以改变的数组,可以对元素进行随机的访问,向ArrayList()中插入与删除元素的速度慢
底层实现是数组,其实就是对数组封装了一些操作,当然这些操作符合List规范,线性方式存储元素,并且元素可以重复
从结构上看ArrayList类,继承了AbstractList抽象类,实现List、RandomAccess、Cloneable、Serializable接口
Collection、AbstractCollection、AbstractList、List在几篇博客都有说。这里不再详细去说
实现Serializable接口启用ArrayList可以序列化的功能
实现Cloneable接口启用ArrayList可以复制的功能
实现RandomAccess表明ArrayList,支持快速(通常是固定时间)随机访问。说白了就是用for(int i =0,i<list.size();i++)比for (Iterator i=list.iterator(); i.hasNext(); )循环的效果好,速度更快
private static final long serialVersionUID = 8683452581122892189L;
/**
* The array buffer into which the elements of the ArrayList are stored.
* The capacity of the ArrayList is the length of this array buffer.
*/
private transient Object[] elementData;
/**
* The size of the ArrayList (the number of elements it contains).
*
* @serial
*/
private int size;
Object[ ] elementData ,ArrayList底层的封装的数组,用于存储元素,这里elementData被transient修饰,表示在序列化并不序列化此参数,但事实并非如此
一般实现可序列化的方法有两种:
1:实现Serializable接口,序列化时候调用 java.io.ObjectOutputStream的defaultWriteObject方法,将对象序列化,此时被transient修饰的参数不会被序列化
2:实现Serializable接口,并提供writeObject方法,这时在序列化时调用这个方法,而不是上边的java.io.ObjectOutputStream的defaultWriteObject方法,这时候
被transient修饰的参数是否序列化取决于这个writeObject方法,在ArrayList提供了这个writeObject方法,在序列化时候将Object [] 一起序列化,这个在解析方法时
候具体说明
int size ,现在ArrayList中元素的个数
public ArrayList(int initialCapacity) {接受带有数组长度参数的构造方法,检查长度合法,初始化数组
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.elementData = new Object[initialCapacity];
}
public ArrayList() {声明一个数组长度为10的ArrayList
this(10);
}
public ArrayList(Collection<? extends E> c) {接受带有集合参数的构造方法,调用集合c的toArray()方法,返回一个数组(这个数组可能不是Object类型的,转化成Object类型)
elementData = c.toArray();
size = elementData.length;
// c.toArray might (incorrectly) not return Object[] (see 6260652)
if (elementData.getClass() != Object[].class)
elementData = Arrays.copyOf(elementData, size, Object[].class);
}
public void trimToSize() {当每次需要动态分配数组长度的时候,int newCapacity = (oldCapacity * 3)/2 + 1; 新的长度基本上是旧长度的1.5倍+ 1,当数组长度比较大,内存又比较吃紧时候,调用trimToSize方法,将无用的内存释放.
modCount++;
int oldCapacity = elementData.length;
if (size < oldCapacity) {
elementData = Arrays.copyOf(elementData, size);
}
}
public void ensureCapacity(int minCapacity) {此方法一般在add中被调用,用于检查数组是否够用,若不够动态非配新的数组,minCapacity是当前数组最少需要的长度
modCount++;
int oldCapacity = elementData.length;
if (minCapacity > oldCapacity) {
Object oldData[] = elementData;
int newCapacity = (oldCapacity * 3)/2 + 1;
if (newCapacity < minCapacity)
newCapacity = minCapacity;
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);
}
}
modCount++ ,这是与迭代器和子列表保持同步时用到,在上几篇博客中有详细说明
public int size() {返回数组大小,就是ArrayList现在的元素个数
return size;
}
public boolean isEmpty() {size为0 ,没有元素,集合为空
return size == 0;
}
public boolean contains(Object o) {这里重写了contains方法,在AbstractCollection中用的是Iterator来迭代整个集合,ArrayList 本身实现了RandomAccess接口,用Iterator遍历集合不如使用for(int i=0;i<size();i++)这种方式遍历效率高,这个方法中调用indexOf(Obejct),其中用的就是上述的遍历方式
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;
}
public Object clone() {重写clone方法,即使重写了clone方法,也是浅克隆。。。
try {
ArrayList<E> v = (ArrayList<E>) super.clone();
v.elementData = Arrays.copyOf(elementData, size);
v.modCount = 0;
return v;
} catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable
throw new InternalError();
}
}
public Object[] toArray() { return Arrays.copyOf(elementData, size); }返回数组,对数组进行截取,放回的数组是正好包含左右元素的,没有空闲的
public <T> T[] toArray(T[] a) {带有类型的数组和长度的数组,这个数组必须是被初始化的,若这数组不能容纳集合中的元素,返回一个装有集合元素的该类型的数组。可以容纳就将原集合数组复制到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;
}
并将这数组的最后一个元素后添加null元素
public E get(int index) {检查下标越界,返回该位置index的元素
RangeCheck(index);
return (E) elementData[index];
}
public E set(int index, E element) {更新元素
RangeCheck(index);
E oldValue = (E) elementData[index];
elementData[index] = element;
return oldValue;
}
public boolean add(E e) {调用ensureCapacityF方法,检查是否还有剩余空间
ensureCapacity(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
public void add(int index, E element) {在指定位置上添加元素,检查下标index,检查剩余空间,将数组从index开始逐个后移一位,将元素插入index位置
if (index > size || index < 0)
throw new IndexOutOfBoundsException(
"Index: "+index+", Size: "+size);
ensureCapacity(size+1); // Increments modCount!!
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
elementData[index] = element;
size++;
}
public E remove(int index) {remove方法
RangeCheck(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; // Let gc do its work
return oldValue;
}
modCount++不多说,将index后的元素逐个向前移动一位,再使末尾的元素置空
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 remove method that skips bounds checking and does not
* return the value removed.
*/
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; // Let gc do its work
}
remove(Object)方法,先找到集合中与Object相等的那个元素的位置,调用fastRemove(index)方法,这里numMoved不可能小于0,只能等于或大于0,等于0时说明该元素在集合的最后一个位置,不能移动其他元素,直接将集合中该元素置空即可,当大于0时候,要先该元素后的元素向前移动一位,再将集合末的元素置空,注意modCount
public void clear() {清空集合中的元素
modCount++;
// Let gc do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
public boolean addAll(Collection<? extends E> c) {获取该集合的数组a,numNew为数组长度,检查集合中的数组空间是否够用,将a从0开始复制numNew个到elementData,从size开始
Object[] a = c.toArray();
int numNew = a.length;
ensureCapacity(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) {numNew 为外部集合的数组的长度,numMoved是原数组需要移动的个数,当numMoved大于0时候,将原数组从index移动到index+numNew的位置(需要为外部集合的数组腾
if (index > size || index < 0)
throw new IndexOutOfBoundsException(
"Index: " + index + ", Size: " + size);
Object[] a = c.toArray();
int numNew = a.length;
ensureCapacity(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;
}
出numNew个位置),移动的长度为numMoved,然后将外部的数组a从0 开始复制到elementData的index,复制numNew个
当numMoved等于0时候,说明直接将数组a复制到原数组的末尾即可
protected void removeRange(int fromIndex, int toIndex) {删除从fromIndex到toIndex范围内的元素,nummoved是要移动元素的个数,将elementData从toIndex拷贝到fromIndex,个数为nummoved
modCount++;
int numMoved = size - toIndex;
System.arraycopy(elementData, toIndex, elementData, fromIndex,
numMoved);
// Let gc do its work
int newSize = size - (toIndex-fromIndex);
while (size != newSize)
elementData[--size] = null;
}
从集合数组的末尾开始删除toIndex-fromIndex个元素
private void RangeCheck(int index) {检查下标
if (index >= size)
throw new IndexOutOfBoundsException(
"Index: "+index+", Size: "+size);
}
private void writeObject(java.io.ObjectOutputStream s)两个方法writeObject和readObject,通过在方法内部对进行序列化操作
throws java.io.IOException{
// Write out element count, and any hidden stuff
int expectedModCount = modCount;
s.defaultWriteObject();
// Write out array length
s.writeInt(elementData.length);
// 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 {
// Read in size, and any hidden stuff
s.defaultReadObject();
// Read in array length and allocate array
int arrayLength = s.readInt();
Object[] a = elementData = new Object[arrayLength];
// Read in all elements in the proper order.
for (int i=0; i<size; i++)
a[i] = s.readObject();
}
s.writeObject(elementData[i]);使得被transient修饰的elementdata数组也能够序列化