/** * Shared empty array instance used for empty instances. * 底层是基于数组实现的 */ privatestaticfinal 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. */ privatestaticfinal Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
/** * ArrayList的元素存储的数组。ArrayList集合的容量就是数组的长度, * The array buffer into which the elements of the ArrayList are stored. * The capacity of the ArrayList is the length of this array buffer. Any * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA * will be expanded to DEFAULT_CAPACITY when the first element is added. * 任何空集合的数组如果等于 DEFAULTCAPACITY_EMPTY_ELEMENTDATA,当第一个元素添加时, * 将会被扩容至默认容量大小。 */ transient Object[] elementData; // non-private to simplify nested class access
/** * Constructs an empty list with an initial capacity of ten. * 构造一个初始化容量为10的空列表(注意:根据注释是10,但是源码其实是一个长度为0的空数组) */ publicArrayList(){ this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA; }
/** * 移除指定位置上的元素,在其右侧元素均向左移动一位(下标减1) */ 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; }
/** * 移除下标最小的所指定的元素,如果不存在,则不变. */ publicbooleanremove(Object o){ if (o == null) { for (int index = 0; index < size; index++) if (elementData[index] == null) { fastRemove(index); returntrue; } } else { for (int index = 0; index < size; index++) if (o.equals(elementData[index])) { fastRemove(index); returntrue; } } returnfalse; }
/** * 根据指定元素,返回第一次出现在这个列表中的下标,如果列表中不包含这个元素,则返回 -1 * 如果元素为空,则返回第一个为null的元素的下标,如果不为空,则比较元素相同,返回第一个 * 相同的下标,如果不存在,则返回-1 */ publicintindexOf(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 */ publicintlastIndexOf(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; }
To Array
1 2
public Object[] toArray() {} public <T> T[] toArray(T[] a) {}
/** * 将集合中装换到指定数组中。如果给定的数组长度小于集合元素个数,则会新创建一个数组,并返回。 * 如果给定的数组长度大于或等于集合元素个数,则直接复制进指定数组,并将剩余空间置为null. * 如果指定数组的运行时类型不是每个元素的运行时类型或父类型时,抛出ArrayStoreException * 如果指定数组为null,则会抛出NullPointerException. * * @Test * public void testToArray(){ * ArrayList<Integer> list = new ArrayList<>(); * list.add(1); * list.add(2); * list.add(3); * * Integer [] arr = new Integer[4]; * Integer[] array = list.toArray(arr); * System.out.println(arr == array);//true * * Integer[] arr1 = new Integer[1]; * Integer[] array1 = list.toArray(arr1); * System.out.println(arr1 == array1);//false * } */ @SuppressWarnings("unchecked") public <T> T[] toArray(T[] a) { if (a.length < size) return (T[]) Arrays.copyOf(elementData, size, a.getClass()); System.arraycopy(elementData, 0, a, 0, size); if (a.length > size) a[size] = null;//将剩余位置置为null. return a; }
Other
1 2 3 4 5 6 7 8
publicintsize(){} publicbooleanisEmpty(){} public Object clone(){} public List<E> subList(int fromIndex, int toIndex){} publicvoidforEach(Consumer<? super E> action){} publicbooleanremoveIf(Predicate<? super E> filter){} publicvoidreplaceAll(UnaryOperator<E> operator){} publicvoidsort(Comparator<? super E> c){}
/** * 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 thrownew InternalError(e); } }
/** * 使用subList(fromIndex,toIndex),返回的是原来集合的一个视图,所以操作的其实是原集合。 * Returns a view of the portion of this list between the specified * 注意:包括fromIndex,不包括toIndex.如果fromIndex和toIndex相等,则返回empty List。 * 当我们需要在当前集合的某些范围内操作,就可以使用subList,例如: * list.subList(fromIndex,toIndex).clear().另外List中的方法同样适用于返回的subList, * 因为subList()返回的SubList集合继承自AbstractList. * 下标越界则抛IndexOutOfBoundsException,参数异常则抛IllegalArgumentException。 */ public List<E> subList(int fromIndex, int toIndex){ //检查集合下标是否合法。 subListRangeCheck(fromIndex, toIndex, size); returnnew SubList(this, 0, fromIndex, toIndex); }
@Test publicvoidtestForeach(){ ArrayList<Integer> list = new ArrayList<>(); list.add(1); list.add(2); list.add(3); list.add(4); for (Integer i : list) { if (i == 2){ list.remove(i); } } System.out.println(list); } //以上代码会抛出 并发修改异常 /* java.util.ConcurrentModificationException at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909) at java.util.ArrayList$Itr.next(ArrayList.java:859) at com.ooyhao.list.ListTest.testForeach(ListTest.java:215) */
使用foreach去增加或删除元素时,会出现并发异常。我们先来看一下反编译的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
@Test publicvoidtestForeach(){ ArrayList<Integer> list = new ArrayList(); list.add(1); list.add(2); list.add(3); list.add(4); Iterator var2 = list.iterator();
while(var2.hasNext()) { Integer i = (Integer)var2.next(); if (i == 2) { list.remove(i); } }
/** * An optimized version of AbstractList.Itr */ privateclassItrimplementsIterator<E> { int cursor; // index of next element to return int lastRet = -1; // index of last element returned; -1 if no such int expectedModCount = modCount;
Itr() {}
publicbooleanhasNext(){ return cursor != size; }
@SuppressWarnings("unchecked") public E next(){ checkForComodification(); int i = cursor; if (i >= size) thrownew NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) thrownew ConcurrentModificationException(); cursor = i + 1; return (E) elementData[lastRet = i]; }
publicvoidremove(){ if (lastRet < 0) thrownew IllegalStateException(); checkForComodification();
@Override @SuppressWarnings("unchecked") publicvoidforEachRemaining(Consumer<? super E> consumer){ Objects.requireNonNull(consumer); finalint size = ArrayList.this.size; int i = cursor; if (i >= size) { return; } final Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) { thrownew ConcurrentModificationException(); } 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(); }
finalvoidcheckForComodification(){ if (modCount != expectedModCount) thrownew ConcurrentModificationException(); } }
/** * An optimized version of AbstractList.ListItr */ privateclassListItrextendsItrimplementsListIterator<E> { ListItr(int index) { super(); cursor = index; }
publicbooleanhasPrevious(){ return cursor != 0; }
publicintnextIndex(){ return cursor; }
publicintpreviousIndex(){ return cursor - 1; }
@SuppressWarnings("unchecked") public E previous(){ checkForComodification(); int i = cursor - 1; if (i < 0) thrownew NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) thrownew ConcurrentModificationException(); cursor = i; return (E) elementData[lastRet = i]; }
publicvoidset(E e){ if (lastRet < 0) thrownew IllegalStateException(); checkForComodification();