前言:在前面我们提到数据结构的线性表。那么今天我们详细看下Java源码是如何实现线性表的,这一篇主要讲解顺序表ArrayList链式表下一篇在提及。
1:ArrayList结构图

2:关于Collection和List的区别
最好的比对就是查看他们的源码我们先看Collection的所有接口
public interface Collection<E> extends Iterable<E> {
int size();
boolean contains(Object o);
Iterator<E> iterator();
Object[] toArray();
<T> T[] toArray(T[] a);
boolean add(E e);
boolean remove(Object o);
boolean containsAll(Collection<?> c);
boolean addAll(Collection<? extends E> c);
boolean retainAll(Collection<?> c);
void clear();
boolean equals(Object o);
int hashCode();
}
</div>
在看List接口
public interface List<E> extends Collection<E> {
int size();
boolean isEmpty();
Iterator<E> iterator();
Object[] toArray();
<T> T[] toArray(T[] a);
boolean add(E e);
boolean remove(Object o);
boolean containsAll(Collection<?> c);
boolean addAll(Collection<? extends E> c);
boolean addAll(int index, Collection<? extends E> c);
boolean removeAll(Collection<?> c);
boolean retainAll(Collection<?> c);
void clear();
boolean equals(Object o);
int hashCode();
E get(int index);
E set(int index, E element);
void add(int index, E element);
E remove(int index);
int indexOf(Object o);
int lastIndexOf(Object o);
ListIterator<E> listIterator();
ListIterator<E> listIterator(int index);
List<E> subList(int fromIndex, int toIndex);
}
</div>
由于List是继承Collection,所有具有Collection所有的功能,从Collection接口中我们也可以看出,Collection不具有索引,不可以取元素的值,而List取可以,List是具有索引的,这样一来在获取元素方面远远好于Collection。
3:Iterable接口
从ArrayList中我们可以看出,最顶端的接口就是Iterable这个接口,这个是一个迭代器,接口如下
public interface Iterable<T> {
Iterator<T> iterator();
}
</div>
这个接口主要是返回一个对象,这个对象是Iterator,那么我们在看看Iterator接口里面的方法
public interface Iterator<E> {
boolean hasNext();
E next();
void remove();
}
</div>
那么我们主要看ArrayList是如何实现迭代器Iterator的。Iterator的实现在AbstractList这个抽象类中的一个私有类Itr中。我们看看具体实现
private class Itr implements Iterator<E> {
int cursor = 0;
int lastRet = -1;
int expectedModCount = modCount;
public boolean hasNext() {
return cursor != size();
}
</div>
cursor:记录即将调用索引的位置
lastRet:最后一个元素的索引
int expectedModCount = modCount;目的是为了验证modCount后面会单独说下。
判断这个集合是否存在最后一个元素,通过cursor != size();size表示数组的长度,因为数组中元素索引从0开始,所以当最后一个索引等于数组长度的时候说明已经到数组的尾部了。
public E next() {
checkForComodification();
try {
E next = get(cursor);
lastRet = cursor++;
return next;
} catch (IndexOutOfBoundsException e) {
checkForComodification();
throw new NoSuchElementException();
}
}
</div>
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
</div>
modCount:记录所有数组数据结构变动的次数,包括添加、删除、更改等,为了避免并发时候,当多个线程同时操作时候,某个线程修改了数组结构,而另一个线程恰恰读取这个数组,这样一来就会产生错误。所以在这段代码中加入了modCount != expectedModCount,比如A线程对数据结构修改一次,那么modCount比如+1,而expectedModCount并没有发生变化,所以这样就会抛出异常。
public void remove() {
if (lastRet == -1)
throw new IllegalStateException();
checkForComodification();
try {
AbstractList.this.remove(lastRet);
if (lastRet < cursor)
cursor--;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException e) {
throw new ConcurrentModificationException();
}
}
</div>
我们刚刚说了lastRet记录的是最后一个元素,所以删除的时候直接按照索引删除即可,因为modCount会减一,所以重新对expectedModCount 进行赋值,避免遍历时候产生错误。而且把lastRed在次赋初始值。
4:分析ArrayList
刚刚目的是为了更加连接ArrayList做个铺垫,ArrayList和我们以前数据结构中提到的顺序表一样,采用Object[] 数组进行存储元素,用size来记录元素的元素的个数。
/** * 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;</div>
关于transient,一旦变量被transient修饰,变量将不再是对象持久化的一部分,那么为啥采用transient修饰呢,由于elementData本身是一个缓存数组,通常会预留一些容量,当容量不够时然后进行扩充,比如现在elementData容量是10,但是只有5个元素,数组中的最后五个元素是没有实际意义的,不需要储存,所以ArrayList的设计者将elementData设计为transient,然后在writeObject方法中手动将其序列化,并且只序列化了实际存储的那些元素,而不是整个数组。我们看下writeObject方法
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 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();
}
}
</div>
关于ArrayList的初始化。ArrayList的设计者采用3种方式初始化。(默认数组容量是10)
public ArrayList(int initialCapacity) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.elementData = new Object[initialCapacity];
}
public ArrayList() {
this(10);
}
public ArrayList(Collection<? extends E> c) {
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);
}
</div>
trimToSize方法,这个方法可能我们好多人用的少,其实意义蛮大的,它主要把没用的容量去除掉,这样一来可以减少内存的开销
public void trimToSize() {
modCount++;
int oldCapacity = elementData.length;
if (size < oldCapacity) {
elementData = Arrays.copyOf(elementData, size);
}
</div>
ensureCapacity方法,我们知道数组如果满了就会进行扩容,这个方法就是扩容的。
public void ensureCapacity(int minCapacity) {
modCount++;
int oldCapacity = elementData.length;
if (minCapacity > oldCapacity) {
Object oldData[] = elementData;
int newCapac

