编码到必定程度以后,但愿本身进一步成长,那就只能经过阅读源码来提高本身。源码不敢说是最优的实现,那也得是比较优秀的实现了。楼主将开启本身的阅读源码之旅,为了让这段旅程能坚持更久,楼主决定从最简单的开始。因此本篇的主角就是ArrayList、虽然网上有大量的文章,对ArrayList实现也有个总体的概念,但我依然以为有阅读的必要,咱们依然能够看看有没有什么细节,须要咱们去注意。数组
经过构造函数,咱们来看看ArrayList定义的时候,都作了什么操做。能够看到源码里面有三个构造函数、分别以下安全
//一个Object数组,用来存储存进来的对象,由于是Object类型的,因此ArrayList并不能存储基本类型数据 //transient 表示序列化的时候,不将该字段进行序列化,那ArrayList什么能够序列化呢?能够看看下面连接的文章 transient Object[] elementData; //静态常量指向一个空数组 private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {}; //静态常量指向一个空数组 private static final Object[] EMPTY_ELEMENTDATA = {}; //无参构造函数 public ArrayList() { //经过无参构造函数构建ArrayList,只会将数组变量指向一个空的数组。 this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; } /** 传入一个初始容量,来构建ArrayList */ public ArrayList(int initialCapacity) { if (initialCapacity > 0) { //若是传过来的数值大于0,则建立一个大小为传进来参数大小的数组。 this.elementData = new Object[initialCapacity]; } else if (initialCapacity == 0) { //若是传过来的数值等于0,则直接将数组引用直接指向一个空数组 this.elementData = EMPTY_ELEMENTDATA; } else { //传过来参数小于0,直接抛出异常 throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity); } } /** 经过传过来一个集合初始化ArrayList */ public ArrayList(Collection<? extends E> c) { //将集合转为Object数组 elementData = c.toArray(); if ((size = elementData.length) != 0) { // c.toArray might (incorrectly) not return Object[] (see 6260652) //c.toArray 可能返回的不是Object数组,暂时不明白什么状况下返回的不是Object[] if (elementData.getClass() != Object[].class) //新建一个数组,元素复制于传进来的集合,赋值给elementData变量 elementData = Arrays.copyOf(elementData, size, Object[].class); } else { // 传进来集合长度为0,则将数组初始化为空数组 this.elementData = EMPTY_ELEMENTDATA; } }复制代码
问:什么存储的数组被定义为transient,ArrayList还能序列化?bash
ArrayList经过Object[]对象来存储数据,只能存对象类型数据,不能存基础类型。构造函数若是不传参数则直接初始化为空数组。传初始化容量,则初始化为传入的容量的数组。传一个集合,初始化为集合内容。markdown
/** *增长元素到尾部 */ public boolean add(E e) { ensureCapacityInternal(size + 1); // 确保数组长度够长,若是不够则扩容 //将元素放到数组中 elementData[size++] = e; return true; } private void ensureCapacityInternal(int minCapacity) { //calculateCapacity() 这个函数计算最小容量。即数组为空数组时返回10,不然为mingCapacity //ensureExplicitCapacity函数将进行容量判断,如须要会进行扩容 ensureExplicitCapacity(calculateCapacity(elementData, minCapacity)); } /** *计算最小容量 *若是第一次插进来数据,数组还没初始化,则默认为max(10,minCapacit), *不然为传进来的参数 */ private static int calculateCapacity(Object[] elementData, int minCapacity) { if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { return Math.max(DEFAULT_CAPACITY, minCapacity); } return 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; //新长度为就长度的1.5倍 int newCapacity = oldCapacity + (oldCapacity >> 1); //若是1.5倍还不够,则直接扩容到传进来的容量 if (newCapacity - minCapacity < 0) newCapacity = minCapacity; //若是容量超过Int的最大值,有些VM会抛出异常 if (newCapacity - MAX_ARRAY_SIZE > 0) newCapacity = hugeCapacity(minCapacity); // minCapacity is usually close to size, so this is a win: //新建一个数组,容量为newCapacity,将就数组复制到新数组中 elementData = Arrays.copyOf(elementData, newCapacity); } 复制代码
往List中增长元素:并发
(1)、若是List还未初始化则初始容量为 max(10,最小须要容量)。app
(2)、若是数组已经初始化,而且剩余容量够存储,则直接将元素存在进去。ide
(3)、若是容量不够,则扩容为 max(原来容量1.5倍,最小须要容量)。函数
再看下往特定位置增长元素oop
public void add(int index, E element) {
//这个函数里面没什么东西,都是传进来的位置index大于已经存储的元素个数,则抛出异常。
rangeCheckForAdd(index);
//判断容量、扩展容量的,这个上面已经有说了
ensureCapacityInternal(size + 1); // Increments modCount!!
//将index位置后面的元素日后移,空出index位置,存放新添加进来的元素
System.arraycopy(elementData, index, elementData, index + 1,size - index);
elementData[index] = element;
size++;
}复制代码
上面为增长单个元素的,再看看增长多个元素是怎么处理的?其实也是差很少的ui
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; }复制代码
//指定位置删除元素 public E remove(int index) { //若是index的位置大于目前已经存储的元素,直接抛出异常 rangeCheck(index); modCount++; //拿到当前index位置的数据 E oldValue = elementData(index); //index后面的元素都须要往前移一位,计算须要日后移动的元素的数量 int numMoved = size - index - 1; //index后面的元素往前移 if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); //最后空出来的位置值为null elementData[--size] = null; // clear to let GC do its work //返回旧的值 return oldValue; }复制代码
public boolean remove(Object o) { //若是是null,则比较用== if (o == null) { for (int index = 0; index < size; index++) //查找出为null的元素位置index if (elementData[index] == null) { //删除index位置元素。将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; } //删除index位置的元素 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 } 复制代码
public boolean removeAll(Collection<?> c) { //若是传进来一个空的集合,抛出NullPointException Objects.requireNonNull(c); //批量删除list中的数据 return batchRemove(c, false); } //***************这里稍微要费点脑看看**************** //这个方法具体的思想就是把不删除的元素移动到数组前头,以后若是有元素须要被删除,则将数组后面位置置为null private boolean batchRemove(Collection<?> c, boolean complement) { final Object[] elementData = this.elementData; int r = 0, w = 0; boolean modified = false; try { //这个for循环的做用就是把不须要移除的元素复制到数组开头 /** 例子[7,9,0,6,8]删除[0,6],通过这个for循环的接口会是[7,9,8 ,6,8] 能够看到三个不须要删除的元素已经被移动数组开头位置,w会是3,指向第一个须要须要被值null的位置 */ 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. /**执行contains方法出现异常的状况,假设上面的例子循环到元素6的时候出现异常 例子[7,9,0,6,8]删除[0,6] for循环的结果仍是[7,9,0,6,8] w会是2,r会是3 */ if (r != size) { /**抛出异常时,循环到的位置的元素及后面的元素,再也不进行删除,因而只有0会被删除,这里就是 把元素6及后面的元素往前拷贝到w的位置,结果就成为[7,9,6,8,8]*/ System.arraycopy(elementData, r, elementData, w, size - r); //w的值值为如今列表删除后应该剩下的元素个数,例子只删了0一个元素,因此w=4 w += size - r; } //有元素被删除,把最后的位置值为null 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; } 复制代码
若是删除指定位置,或者删除传入的某个对象,上面的方法1,2,则定位到元素的位置,以后将要删除位置后面的元素往前移一位,将数组最后一个元素位置置为null。这个应该很好理解,数组删除元素就是移动元素。
若是删除指定集合中的元素,则将不须要删除的元素直接移动到数组开头位置,异常状况下,则移动到开头的包括两部分((1)异常发生位置前,不须要被删除的元素;(2)异常发生位置后面的全部元素),以后再将数组后面不须要的位置置为null
这个不用看代码,有没都知道它只能遍历数组去查
public boolean contains(Object o) { return indexOf(o) >= 0; } /**从前日后遍历,找指定元素,找不到则返回-1*/ 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; } /**从后面往前查找定位某元素位置,不存在则返回-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; }复制代码
/** 克隆出一个ArrayList,返回,这里返回的对象是克隆出来的新对象, 操做新对形象,并不会影响原来的ArrayList */ public Object clone() { try { ArrayList<?> v = (ArrayList<?>) 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(e); } } /** 拷贝出一个新的数组返回 */ public Object[] toArray() { return Arrays.copyOf(elementData, size); } /** 这个方法得注意下了: (1)、传入的数组长度比ArrayList存储的元素个数小,则会返回一个新的数组, 传进来的数组并不会拷贝ArrayList中的元素 (2)、传进来的数组长度大于等于ArrayList中存储的元素个数,则只会将ArrayList中的元素拷贝到传进来的 数组里面,并返回该数组 */ public <T> T[] toArray(T[] 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; }复制代码
这里比较简单,不过得⚠️注意下toArray(T[] a)这个方法,可能一不当心会写出Bug。
/** 实现Iterator接口,ArrayList定义的内部类,迭代器类 */ private class Itr implements Iterator<E> { int cursor; // index of next element to return int lastRet = -1; // index of last element returned; -1 if no such /** 这个很关键,modCount,上面的代码屡次出现此变量,咱们没作出解释. 其实他的用处是这里,每次修改List,modCount都会自增, 因此能够看作是ArrayList当前数据的版本,一会会用到. */ int expectedModCount = modCount; Itr() {} /**判断是否还有下一个值,若是游标不等于元素个数,则还有下一个值*/ public boolean hasNext() { return cursor != size; } /** 拿到下一个值* */ @SuppressWarnings("unchecked") public E next() { /**上面说的版本号,就用到这里了,若是迭代器使用期间, 有其余线程修改了ArrayList,那么迭代器会直接抛出ConcurrentModificationException异常。 ArrayList是非线程安全的,迭代器采用快速失败的方法,一旦有线程修改数据,迭代就会失败。 */ checkForComodification(); int i = cursor; //若是游标值大于元素个数,直接抛出异常 if (i >= size) 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() { //lastRet 上一次返回元素位置,若是<0,说明尚未使用next遍历,直接抛出异常 if (lastRet < 0) throw new IllegalStateException(); //并发抛出异常 checkForComodification(); try { //删除指定位置的元素 ArrayList.this.remove(lastRet); /*游标指向被删除元素位置, 例子:[5,7,9,6],删除7,调next返回7后,cursor此时应该是2,指向"9"的位置,lastRet为1,指向“7” 删除后列表为[5,9,6],cursor置为1,指向“9” */ cursor = lastRet; lastRet = -1; //修改迭代器版本号 expectedModCount = modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } /** 自动遍历游标以后的全部元素,交给consumer去处理 */ @Override @SuppressWarnings("unchecked") public void forEachRemaining(Consumer<? super E> consumer) { //consumer不能为空,不然抛异常 Objects.requireNonNull(consumer); final int size = ArrayList.this.size; int i = cursor; if (i >= size) { return; } final Object[] elementData = ArrayList.this.elementData; //被其余线程修改了,直接抛出异常 if (i >= elementData.length) { throw new ConcurrentModificationException(); } //while里面遍历游标到结束位置的全部元素,交给consumer去处理 while (i != size && modCount == expectedModCount) { consumer.accept((E) elementData[i++]); } // update once at end of iteration to reduce heap write traffic cursor = i; lastRet = i - 1; checkForComodification(); } //返回是否并发修改了ArrayList final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } }复制代码
/**实现ListIterator接口,继承自上面的Itr 遍历器,提供了从后往前遍历,还有修改元素,增长元素*/ private class ListItr extends Itr implements ListIterator<E> { ListItr(int index) { super(); cursor = index; } //往前遍历,是否还有下一个元素 public boolean hasPrevious() { return cursor != 0; } public int nextIndex() { return cursor; } public int previousIndex() { return cursor - 1; } //往前遍历,返回元素 @SuppressWarnings("unchecked") public E previous() { checkForComodification(); int i = cursor - 1; if (i < 0) throw new NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) throw new ConcurrentModificationException(); cursor = i; return (E) elementData[lastRet = i]; } //修改元素,直接set一个元素过来 public void set(E e) { if (lastRet < 0) throw new IllegalStateException(); checkForComodification(); try { ArrayList.this.set(lastRet, e); } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } //增长元素,调用add方法增长 public void add(E e) { checkForComodification(); try { int i = cursor; ArrayList.this.add(i, e); cursor = i + 1; lastRet = -1; expectedModCount = modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } }复制代码
迭代器,这里代码也比较简单,要注意的主要有几个点:(1)、ArrayList是非线程安全的,一旦有其余线程修改了,迭代器采用快速失败的方法,直接抛出异常。(2)、ListItertor相对Itertor,除了日后遍历,还能够往前遍历。(3)、ListItertor比Itertor多了增长元素,修改元素的方法。
到此,ArrayList的代码基本解析完毕,这里还须要明确的几个点:
(1)、ArrayList采用数组来存储,数组长度是是不容许扩展的,ArrayList扩展经过,建立一个新数组,并将旧数组元素拷贝到新数组,实现扩展。
(2)、数组结构存在乎味着指定位置获取元素,是比较快的,时间复杂度是O(1),而删除元素、增长元素涉及元素移动,时间复杂度是O(n)。