-
private void fastRemove(Object[ ] es, int i)
官方直译:专用的remove方法,跳过边界检查,并且不返回删除的值。
private void fastRemove(Object[] es, int i) { modCount++; final int newSize; // 数组大小-1,并判断i是否在数组范围内 if ((newSize = size - 1) > i) // 将i+1之后的元素依次赋值到i之后 System.arraycopy(es, i + 1, es, i, newSize - i); // es的末尾置为空,因为并未变化数组容量,所以将后面未存放的置为空 es[size = newSize] = null; }
-
public void clear( )
官方直译:从此列表中删除所有元素。该调用返回后,列表将变为空。
// 无需赘言 public void clear() { modCount++; final Object[] es = elementData; // 这个for里的东西写的妙啊,既用to存size用于循环又将size归零 for (int to = size, i = size = 0; i < to; i++) es[i] = null; }
-
public boolean addAll(Collection<? extends E> c)
官方直译:按照指定集合的迭代器返回的顺序,将指定集合中的所有元素追加到此列表的末尾。如果在操作过程中修改了指定的集合,则此操作的行为是不确定的。(这意味着如果指定的集合是此列表,并且此列表是非空的,则此调用的行为是未定义的。)
public boolean addAll(Collection<? extends E> c) { // 先将c数组化(如果有需要的话) Object[] a = c.toArray(); modCount++; int numNew = a.length; if (numNew == 0) // 报错 return false; Object[] elementData; final int s; if (numNew > (elementData = this.elementData).length - (s = size)) // elementData容量扩为s+numNew elementData = grow(s + numNew); // 将a从0开始的numNew长的数组赋值给elementData的s之后 System.arraycopy(a, 0, elementData, s, numNew); size = s + numNew; return true; }
-
public boolean addAll(int index, Collection<? extends E> c)
官方直译:从指定位置开始,将指定集合中的所有元素插入此列表。将当前位于该位置的元素(如果有)和任何后续元素向右(增加其索引)。新元素将按指定集合的迭代器返回的顺序显示在列表中。
个人理解:与12方法不同的地方在于多传递了个index参数,该参数为将集合c中所有元素从index处插入,后续的元素后移。
public boolean addAll(int index, Collection<? extends E> c) { // 检查index是否合法 rangeCheckForAdd(index); // 将c转为Array存储于a[]中 Object[] a = c.toArray(); modCount++; int numNew = a.length; if (numNew == 0) return false; Object[] elementData; final int s; // 如果所需容量大于原开辟的所剩容量时,则原elementData进行扩展至s+numNew大小 if (numNew > (elementData = this.elementData).length - (s = size)) elementData = grow(s + numNew); // numMoved为需要移位的元素数量 int numMoved = s - index; if (numMoved > 0) //与13不同之处:这第一步是先移动index之后的元素 System.arraycopy(elementData, index, elementData, index + numNew, numMoved); // 然后这里将添加进的a(c)赋值进中间空出来这一段中 System.arraycopy(a, 0, elementData, index, numNew); size = s + numNew; return true; }
-
protected void removeRange(int fromIndex, int toIndex)
官方直译:从此列表中删除所有索引在fromIndex(含)和toIndex(互斥)之间的所有元素。 将任何后续元素向左移动(减少其索引)。 此调用通过toIndex-fromIndex元素来缩短列表。(注意:如果toIndex == fromIndex,则此操作无效。)
个人理解:fromIndex为删除开始位置,toIndex为直到toIndex的位置。
protected void removeRange(int fromIndex, int toIndex) { // 判定参数是否合法 if (fromIndex > toIndex) { throw new IndexOutOfBoundsException( outOfBoundsMsg(fromIndex, toIndex)); } modCount++; // 调用内置删除方法 shiftTailOverGap(elementData, fromIndex, toIndex); }
-
private void shiftTailOverGap(Object[] es, int lo, int hi)
官方直译:通过向下滑动以下元素来消除从lo到hi的间隙。
个人理解:通过下移操作将es[]数组中high部分与low部分中的数据清除。
private void shiftTailOverGap(Object[] es, int lo, int hi) { // 将es中hi之后的size-hi位数据赋值于lo之后,并将lo+size-hi之后置空 System.arraycopy(es, hi, es, lo, size - hi); // 这个for写的妙啊! for (int to = size, i = (size -= hi - lo); i < to; i++) es[i] = null; }
-
private void rangeCheckForAdd(int index)
官方直译:add和addAll使用的rangeCheck版本。
上方用于检查index是否合法的检测方法。
private void rangeCheckForAdd(int index) { // 规定index合法区域为0 <= index <= size,若未在合法区域内抛出IndexOut异常。 if (index > size || index < 0) throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); }
-
private String outOfBoundsMsg(int index)
官方直译:构造一个IndexOutOfBoundsException异常详细消息。
错误处理代码的许多可能的重构,这种“概述”执行最好的服务器和客户端的虚拟机。
private String outOfBoundsMsg(int index) { return "Index: "+index+", Size: "+size; }
-
private static String outOfBoundsMsg(int fromIndex, int toIndex)
官方直译:用于检查(fromIndex> toIndex)条件的版本。
private static String outOfBoundsMsg(int fromIndex, int toIndex) { return "From Index: " + fromIndex + " > To Index: " + toIndex; }
-
public boolean removeAll(Collection<?> c)
官方直译:从此数组列表中删除指定的集合c中包含的所有元素。
public boolean removeAll(Collection<?> c) { // 调用私有方法batchRemove进行删除操作(隐藏删除操作) return batchRemove(c, false, 0, size); }
-
public boolean retainAll(Collection<?> c)
官方直译:只保留此列表中包含在指定集合中的元素。 换句话说,从这个列表中的所有元素删除所有未包含在指定的colleciton即c的元素。
public boolean retainAll(Collection<?> c) { // 调用私有方法batchRemove进行保留操作(操作) return batchRemove(c, true, 0, size); }
-
boolean batchRemove(Collection<?> c, boolean complement, final int from, final int end)
个人理解:函数名为批量删除,未用public定义,故为内部方法,隐藏删除细节。多么美妙的方法!
boolean batchRemove(Collection<?> c, boolean complement, final int from, final int end) { // 判断c是否为空集合 Objects.requireNonNull(c); final Object[] es = elementData; int r; // Optimize for initial run of survivors for (r = from;; r++) { if (r == end) return false; /* 若c中包含/不包含第r个元素时,跳出循环,找到第一个开始保留或删除的起始元素的起点 complement为false时为删除c中所有,为true为保留c中所有*/ if (c.contains(es[r]) != complement) break; } // 在r之前的都可以直接抹去,因为不符合条件 int w = r++; try { // 妙啊 for (Object e; r < end; r++) if (c.contains(e = es[r]) == complement) // 符合条件的全部留下来并存入es es[w++] = e; } catch (Throwable ex) { // ????????这个catch是如何处理的? // Preserve behavioral compatibility with AbstractCollection, // even if c.contains() throws. System.arraycopy(es, r, es, w, end - r); w += end - r; throw ex; } finally { //modCount统计的最终进行了多少次批量操作 modCount += end - w; //将es中w到end的那一部分抹掉 shiftTailOverGap(es, w, end); } return true; }
-
private void writeObject(java.io.ObjectOutputStream s)
官方直译:将实例的状态保存到流(即,对其进行序列化)。
个人理解:就是将该数组对象进行序列化。这个方法没有学懂
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 behavioral 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(); } }
-
private void readObject(java.io.ObjectInputStream s)
官方直译:从流中重构此实例(即反序列化)。
个人不是很理解。
private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { // Read in size, and any hidden stuff s.defaultReadObject(); // Read in capacity s.readInt(); // ignored if (size > 0) { // like clone(), allocate array based upon size not capacity SharedSecrets.getJavaObjectInputStreamAccess().checkArray(s, Object[].class, size); Object[] elements = new Object[size]; // Read in all elements in the proper order. for (int i = 0; i < size; i++) { elements[i] = s.readObject(); } elementData = elements; } else if (size == 0) { elementData = EMPTY_ELEMENTDATA; } else { throw new java.io.InvalidObjectException("Invalid size: " + size); } }
-
public ListIterator listIterator(int index)及相关方法
官方直译:
个人理解:
public ListIterator<E> listIterator(int index) { rangeCheckForAdd(index); return new ListItr(index); } public ListIterator<E> listIterator() { return new ListItr(0); } public Iterator<E> iterator() { return new Itr(); }
上述使用到的ListItr()及Itr()方法:
/** * 一个优化后的抽象Itr版本——内部类 */ private class Itr implements Iterator<E> { int cursor; // 下一个要返回元素的索引 int lastRet = -1; // 返回的上一个元素的索引,初始态-1 //预期的修改次数 int expectedModCount = modCount; // prevent creating a synthetic constructor Itr() {} //检查是否还有下个元素 public boolean hasNext() { return cursor != size; } //返回下一个元素 @SuppressWarnings("unchecked") public E next() { 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() { if (lastRet < 0) throw new IllegalStateException(); checkForComodification(); try { ArrayList.this.remove(lastRet); cursor = lastRet; lastRet = -1; expectedModCount = modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } //这个内部类方法不是很看懂,大致是保留action的所有? @Override public void forEachRemaining(Consumer<? super E> action) { Objects.requireNonNull(action); final int size = ArrayList.this.size; int i = cursor; if (i < size) { final Object[] es = elementData; if (i >= es.length) throw new ConcurrentModificationException(); for (; i < size && modCount == expectedModCount; i++) action.accept(elementAt(es, i)); // update once at end to reduce heap write traffic cursor = i; lastRet = i - 1; checkForComodification(); } } //用于检查线程是否同步吧? final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } }
Java 集合中常见 checkForComodification()方法的作用?
答:主要是用来实现fail-fast机制。
有两个线程(线程A,线程B),其中线程A负责遍历list、线程B修改list。 -线程A在遍历list过程的某个时候(此时expectedModCount = modCount=N),线程启动, 同时线程B增加一个元素,这是modCount的值发生改变(modCount + 1 = N + 1)。 线程A继续遍历执行next方法时, 通告checkForComodification方法发现expectedModCount = N , 而modCount = N + 1,两者不等, 这时就抛出ConcurrentModificationException 异常,从而产生fail-fast机制。
摘自CSDN博客
/** * 一个优化后的抽象集合ListItr版本——内部类 * Itr为ListItr的父类 */ 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]; } public void set(E e) { if (lastRet < 0) throw new IllegalStateException(); checkForComodification(); try { ArrayList.this.set(lastRet, e); } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } 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(); } } }
ArrayList源码浅析(二)
最新推荐文章于 2022-07-05 10:46:09 发布