国产xxxx99真实实拍_久久不雅视频_高清韩国a级特黄毛片_嗯老师别我我受不了了小说

資訊專欄INFORMATION COLUMN

ArrayList源碼解讀(二)

HtmlCssJs / 1151人閱讀

摘要:刪除錯有緩沖區(qū)里的數(shù)據(jù)實際存儲數(shù)據(jù)置,從到實際存儲的位置循環(huán)置添加集合到當(dāng)前集合轉(zhuǎn)化為數(shù)組添加數(shù)據(jù)長度長度為直接返回舊數(shù)據(jù)長度新數(shù)據(jù)長度大于緩沖區(qū)大小,就擴容擴大為可以容納舊數(shù)據(jù)新數(shù)據(jù)大小新數(shù)據(jù)從位開始復(fù)制到緩沖區(qū)的位處,復(fù)制長度為新數(shù)據(jù)

clear()刪除錯有緩沖區(qū)里的數(shù)據(jù)

public void clear() {
        modCount++;
        final Object[] es = elementData;
        for (int to = size, i = size = 0; i < to; i++)//實際存儲數(shù)據(jù)置0,從0到實際存儲的位置循環(huán)置null
            es[i] = null;
    }

addAll(Collection c)添加集合到當(dāng)前集合

 public boolean addAll(Collection c) {
        Object[] a = c.toArray();//轉(zhuǎn)化為數(shù)組
        modCount++;
        int numNew = a.length;//添加數(shù)據(jù)長度
        if (numNew == 0)
            return false;//長度為0直接返回false
        Object[] elementData;
        final int s;
        if (numNew > (elementData = this.elementData).length - (s = size))//舊數(shù)據(jù)長度+新數(shù)據(jù)長度大于緩沖區(qū)大小,就擴容
            elementData = grow(s + numNew);//擴大為可以容納舊數(shù)據(jù)+新數(shù)據(jù)大小
        System.arraycopy(a, 0, elementData, s, numNew);//新數(shù)據(jù)從0位開始復(fù)制到緩沖區(qū)的s位處,復(fù)制長度為新數(shù)據(jù)長度
        size = s + numNew;
        return true;
    }

addAll(int index, Collection c)添加集合到當(dāng)前集合的固定位置

 public boolean addAll(int index, Collection c) {
        rangeCheckForAdd(index);//確認(rèn)下標(biāo)

        Object[] a = c.toArray();//轉(zhuǎn)數(shù)組
        modCount++;
        int numNew = a.length;
        if (numNew == 0)
            return false;//長度為0直接返回
        Object[] elementData;
        final int s;
        if (numNew > (elementData = this.elementData).length - (s = size))//舊數(shù)據(jù)長度+新數(shù)據(jù)長度大于緩沖區(qū)大小,就擴容
            elementData = grow(s + numNew);

        int numMoved = s - index;//存儲長度減去index得出就是要移動數(shù)據(jù)的長度
        if (numMoved > 0)
            System.arraycopy(elementData, index,elementData, index + numNew,numMoved);//把緩沖區(qū)從index移動到index + numNew,移動長度為numMoved 
        System.arraycopy(a, 0, elementData, index, numNew);//把集合從0位移動到緩沖區(qū)index位,共移動集合的長度個數(shù)據(jù)
        size = s + numNew;//實際存儲數(shù)更改為size+集合長度
        return true;//返回true
    }

removeRange(int fromIndex, int toIndex)刪除介于(包含)fromIndex和toIndex(不包含)的所有元素

  protected void removeRange(int fromIndex, int toIndex) {
        if (fromIndex > toIndex) {
            throw new IndexOutOfBoundsException(
                    outOfBoundsMsg(fromIndex, toIndex));
        }
        modCount++;
        shiftTailOverGap(elementData, fromIndex, toIndex);
    }

shiftTailOverGap(Object[] es, int lo, int hi)刪除lo(包含)到hi(不包含)期間的元素

 private void shiftTailOverGap(Object[] es, int lo, int hi) {
        System.arraycopy(es, hi, es, lo, size - hi);//從hi位以后的數(shù)據(jù)復(fù)制到lo位,共復(fù)制size-hi個數(shù)據(jù)
        for (int to = size, i = (size -= hi - lo); i < to; i++)
            es[i] = null;//置0
    }

rangeCheckForAdd(int index)判斷是否在區(qū)間內(nèi)

private void rangeCheckForAdd(int index) {
        if (index > size || index < 0)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

下標(biāo)越界消息

private String outOfBoundsMsg(int index) {
        return "Index: "+index+", Size: "+size;
    }
    
    
private static String outOfBoundsMsg(int fromIndex, int toIndex) {
        return "From Index: " + fromIndex + " > To Index: " + toIndex;
    }

removeAll(Collection c) 刪除緩沖區(qū)中,集合包含的數(shù)據(jù)

 public boolean removeAll(Collection c) {
        return batchRemove(c, false, 0, size);
    }

retainAll(Collection c)保留緩沖區(qū)中,集合包含的數(shù)據(jù)

public boolean retainAll(Collection c) {
        return batchRemove(c, true, 0, size);
    }

batchRemove(Collection c, boolean complement,final int from, final int end)false是刪除傳入集合包含元素,true是保留傳入集合包含元素

boolean batchRemove(Collection c, boolean complement,
                        final int from, final int end) {
        Objects.requireNonNull(c);
        final Object[] es = elementData;
        int r;
        // Optimize for initial run of survivors
        for (r = from;; r++) {
            if (r == end)//操作長度為0直接返回false
                return false;
            if (c.contains(es[r]) != complement)//為true的時候,查找到第一個不保留位r。為false時候查找到第一個要刪除的位
                break;
        }
        int w = r++;
        try {
            for (Object e; r < end; r++)
                if (c.contains(e = es[r]) == complement)//為true時把在集合的元素往前移,為false時,不在集合的元素往前移動
                    es[w++] = e;
        } catch (Throwable ex) {
            // 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 += end - w;
            shiftTailOverGap(es, w, end);//刪除尾部元素
        }
        return true;
    }

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

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) {//數(shù)據(jù)量大于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) {//數(shù)據(jù)量等于0
            elementData = EMPTY_ELEMENTDATA;
        } else {
            throw new java.io.InvalidObjectException("Invalid size: " + size);
        }
    }

listIterator()返回迭代器

public ListIterator listIterator() {
        return new ListItr(0);
    }

listIterator(int index)返回迭代器

public ListIterator listIterator(int index) {
        rangeCheckForAdd(index);//
        return new ListItr(index);
    }
Itr內(nèi)部類
private class Itr implements Iterator {
        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();//光標(biāo)越界
            Object[] elementData = ArrayList.this.elementData;//緩沖區(qū)
            if (i >= elementData.length)
                throw new ConcurrentModificationException();//線程不安全
            cursor = i + 1;
            return (E) elementData[lastRet = i];//最后一個元素的索引改成i
        }

        public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();

            try {
                ArrayList.this.remove(lastRet);//移除最后返回的元素
                cursor = lastRet;//光標(biāo)回退
                lastRet = -1;//最后返回的元素被刪除,索引變?yōu)?1
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

        @Override
        public void forEachRemaining(Consumer action) {//循環(huán)剩余
            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));//把緩沖區(qū)es中i處元素放進accept方法里
                // update once at end to reduce heap write traffic
                cursor = i;
                lastRet = i - 1;
                checkForComodification();
            }
        }

        final void checkForComodification() {//線程安全
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }

subList(int fromIndex, int toIndex)返回集合的部分(類型變成了SubList)

public List subList(int fromIndex, int toIndex) {
        subListRangeCheck(fromIndex, toIndex, size);
        return new SubList<>(this, fromIndex, toIndex);
    }
ListItr 內(nèi)部類
 private class ListItr extends Itr implements ListIterator {
        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;//光標(biāo)前移
            return (E) elementData[lastRet = i];
        }

        public void set(E e) {
            if (lastRet < 0)//最后操作位必須大于0,即進行刪除操作后得滑動索引,不然會報IllegalStateException
                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;//后移光標(biāo)
                lastRet = -1;//清空最后操作元素
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }
    }

subList(int fromIndex, int toIndex)

public List subList(int fromIndex, int toIndex) {
        subListRangeCheck(fromIndex, toIndex, size);
        return new SubList<>(this, fromIndex, toIndex);
    }
靜態(tài)內(nèi)部類SubList
private static class SubList extends AbstractList implements RandomAccess {
        private final ArrayList root;
        private final SubList parent;
        private final int offset;
        private int size;

        /**
         * Constructs a sublist of an arbitrary ArrayList.
         */
        public SubList(ArrayList root, int fromIndex, int toIndex) {
            this.root = root;
            this.parent = null;
            this.offset = fromIndex;
            this.size = toIndex - fromIndex;
            this.modCount = root.modCount;
        }

        /**
         * Constructs a sublist of another SubList.
         */
        private SubList(SubList parent, int fromIndex, int toIndex) {
            this.root = parent.root;
            this.parent = parent;
            this.offset = parent.offset + fromIndex;
            this.size = toIndex - fromIndex;
            this.modCount = root.modCount;
        }

        public E set(int index, E element) {
            Objects.checkIndex(index, size);
            checkForComodification();
            E oldValue = root.elementData(offset + index);
            root.elementData[offset + index] = element;
            return oldValue;
        }

        public E get(int index) {
            Objects.checkIndex(index, size);
            checkForComodification();
            return root.elementData(offset + index);
        }

        public int size() {
            checkForComodification();
            return size;
        }

        public void add(int index, E element) {
            rangeCheckForAdd(index);
            checkForComodification();
            root.add(offset + index, element);
            updateSizeAndModCount(1);
        }

        public E remove(int index) {
            Objects.checkIndex(index, size);
            checkForComodification();
            E result = root.remove(offset + index);
            updateSizeAndModCount(-1);
            return result;
        }

        protected void removeRange(int fromIndex, int toIndex) {
            checkForComodification();
            root.removeRange(offset + fromIndex, offset + toIndex);
            updateSizeAndModCount(fromIndex - toIndex);
        }

        public boolean addAll(Collection c) {
            return addAll(this.size, c);
        }

        public boolean addAll(int index, Collection c) {
            rangeCheckForAdd(index);
            int cSize = c.size();
            if (cSize==0)
                return false;
            checkForComodification();
            root.addAll(offset + index, c);
            updateSizeAndModCount(cSize);
            return true;
        }

        public void replaceAll(UnaryOperator operator) {
            root.replaceAllRange(operator, offset, offset + size);
        }

        public boolean removeAll(Collection c) {
            return batchRemove(c, false);
        }

        public boolean retainAll(Collection c) {
            return batchRemove(c, true);
        }

        private boolean batchRemove(Collection c, boolean complement) {
            checkForComodification();
            int oldSize = root.size;
            boolean modified =
                root.batchRemove(c, complement, offset, offset + size);
            if (modified)
                updateSizeAndModCount(root.size - oldSize);
            return modified;
        }

        public boolean removeIf(Predicate filter) {
            checkForComodification();
            int oldSize = root.size;
            boolean modified = root.removeIf(filter, offset, offset + size);
            if (modified)
                updateSizeAndModCount(root.size - oldSize);
            return modified;
        }

        public Object[] toArray() {
            checkForComodification();
            return Arrays.copyOfRange(root.elementData, offset, offset + size);
        }

        @SuppressWarnings("unchecked")
        public  T[] toArray(T[] a) {
            checkForComodification();
            if (a.length < size)
                return (T[]) Arrays.copyOfRange(
                        root.elementData, offset, offset + size, a.getClass());
            System.arraycopy(root.elementData, offset, a, 0, size);
            if (a.length > size)
                a[size] = null;
            return a;
        }

        public boolean equals(Object o) {
            if (o == this) {
                return true;
            }

            if (!(o instanceof List)) {
                return false;
            }

            boolean equal = root.equalsRange((List)o, offset, offset + size);
            checkForComodification();
            return equal;
        }

        public int hashCode() {
            int hash = root.hashCodeRange(offset, offset + size);
            checkForComodification();
            return hash;
        }

        public int indexOf(Object o) {
            int index = root.indexOfRange(o, offset, offset + size);
            checkForComodification();
            return index >= 0 ? index - offset : -1;
        }

        public int lastIndexOf(Object o) {
            int index = root.lastIndexOfRange(o, offset, offset + size);
            checkForComodification();
            return index >= 0 ? index - offset : -1;
        }

        public boolean contains(Object o) {
            return indexOf(o) >= 0;
        }

        public Iterator iterator() {
            return listIterator();
        }

        public ListIterator listIterator(int index) {
            checkForComodification();
            rangeCheckForAdd(index);

            return new ListIterator() {
                int cursor = index;
                int lastRet = -1;
                int expectedModCount = root.modCount;

                public boolean hasNext() {
                    return cursor != SubList.this.size;
                }

                @SuppressWarnings("unchecked")
                public E next() {
                    checkForComodification();
                    int i = cursor;
                    if (i >= SubList.this.size)
                        throw new NoSuchElementException();
                    Object[] elementData = root.elementData;
                    if (offset + i >= elementData.length)
                        throw new ConcurrentModificationException();
                    cursor = i + 1;
                    return (E) elementData[offset + (lastRet = i)];
                }

                public boolean hasPrevious() {
                    return cursor != 0;
                }

                @SuppressWarnings("unchecked")
                public E previous() {
                    checkForComodification();
                    int i = cursor - 1;
                    if (i < 0)
                        throw new NoSuchElementException();
                    Object[] elementData = root.elementData;
                    if (offset + i >= elementData.length)
                        throw new ConcurrentModificationException();
                    cursor = i;
                    return (E) elementData[offset + (lastRet = i)];
                }

                public void forEachRemaining(Consumer action) {
                    Objects.requireNonNull(action);
                    final int size = SubList.this.size;
                    int i = cursor;
                    if (i < size) {
                        final Object[] es = root.elementData;
                        if (offset + i >= es.length)
                            throw new ConcurrentModificationException();
                        for (; i < size && modCount == expectedModCount; i++)
                            action.accept(elementAt(es, offset + i));
                        // update once at end to reduce heap write traffic
                        cursor = i;
                        lastRet = i - 1;
                        checkForComodification();
                    }
                }

                public int nextIndex() {
                    return cursor;
                }

                public int previousIndex() {
                    return cursor - 1;
                }

                public void remove() {
                    if (lastRet < 0)
                        throw new IllegalStateException();
                    checkForComodification();

                    try {
                        SubList.this.remove(lastRet);
                        cursor = lastRet;
                        lastRet = -1;
                        expectedModCount = root.modCount;
                    } catch (IndexOutOfBoundsException ex) {
                        throw new ConcurrentModificationException();
                    }
                }

                public void set(E e) {
                    if (lastRet < 0)
                        throw new IllegalStateException();
                    checkForComodification();

                    try {
                        root.set(offset + lastRet, e);
                    } catch (IndexOutOfBoundsException ex) {
                        throw new ConcurrentModificationException();
                    }
                }

                public void add(E e) {
                    checkForComodification();

                    try {
                        int i = cursor;
                        SubList.this.add(i, e);
                        cursor = i + 1;
                        lastRet = -1;
                        expectedModCount = root.modCount;
                    } catch (IndexOutOfBoundsException ex) {
                        throw new ConcurrentModificationException();
                    }
                }

                final void checkForComodification() {
                    if (root.modCount != expectedModCount)
                        throw new ConcurrentModificationException();
                }
            };
        }

        public List subList(int fromIndex, int toIndex) {
            subListRangeCheck(fromIndex, toIndex, size);
            return new SubList<>(this, fromIndex, toIndex);
        }

        private void rangeCheckForAdd(int index) {
            if (index < 0 || index > this.size)
                throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
        }

        private String outOfBoundsMsg(int index) {
            return "Index: "+index+", Size: "+this.size;
        }

        private void checkForComodification() {
            if (root.modCount != modCount)
                throw new ConcurrentModificationException();
        }

        private void updateSizeAndModCount(int sizeChange) {
            SubList slist = this;
            do {
                slist.size += sizeChange;
                slist.modCount = root.modCount;
                slist = slist.parent;
            } while (slist != null);
        }

        public Spliterator spliterator() {
            checkForComodification();

            // ArrayListSpliterator not used here due to late-binding
            return new Spliterator() {
                private int index = offset; // current index, modified on advance/split
                private int fence = -1; // -1 until used; then one past last index
                private int expectedModCount; // initialized when fence set

                private int getFence() { // initialize fence to size on first use
                    int hi; // (a specialized variant appears in method forEach)
                    if ((hi = fence) < 0) {
                        expectedModCount = modCount;
                        hi = fence = offset + size;
                    }
                    return hi;
                }

                public ArrayList.ArrayListSpliterator trySplit() {
                    int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
                    // ArrayListSpliterator can be used here as the source is already bound
                    return (lo >= mid) ? null : // divide range in half unless too small
                        root.new ArrayListSpliterator(lo, index = mid, expectedModCount);
                }

                public boolean tryAdvance(Consumer action) {
                    Objects.requireNonNull(action);
                    int hi = getFence(), i = index;
                    if (i < hi) {
                        index = i + 1;
                        @SuppressWarnings("unchecked") E e = (E)root.elementData[i];
                        action.accept(e);
                        if (root.modCount != expectedModCount)
                            throw new ConcurrentModificationException();
                        return true;
                    }
                    return false;
                }

                public void forEachRemaining(Consumer action) {
                    Objects.requireNonNull(action);
                    int i, hi, mc; // hoist accesses and checks from loop
                    ArrayList lst = root;
                    Object[] a;
                    if ((a = lst.elementData) != null) {
                        if ((hi = fence) < 0) {
                            mc = modCount;
                            hi = offset + size;
                        }
                        else
                            mc = expectedModCount;
                        if ((i = index) >= 0 && (index = hi) <= a.length) {
                            for (; i < hi; ++i) {
                                @SuppressWarnings("unchecked") E e = (E) a[i];
                                action.accept(e);
                            }
                            if (lst.modCount == mc)
                                return;
                        }
                    }
                    throw new ConcurrentModificationException();
                }

                public long estimateSize() {
                    return getFence() - index;
                }

                public int characteristics() {
                    return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
                }
            };
        }
    }

forEach(Consumer action)迭代元素

 @Override
    public void forEach(Consumer action) {
        Objects.requireNonNull(action);
        final int expectedModCount = modCount;
        final Object[] es = elementData;//緩沖區(qū)
        final int size = this.size;
        for (int i = 0; modCount == expectedModCount && i < size; i++)//循環(huán)0到實際長度
            action.accept(elementAt(es, i));//對應(yīng)下標(biāo)值放入accept方法
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();//線程安全
    }

spliterator() 返回分裂器

 @Override
    public Spliterator spliterator() {
        return new ArrayListSpliterator(0, -1, 0);
    }
內(nèi)部類ArrayListSpliterator (基于索引的二分裂,懶惰初始化的Spliterator)
final class ArrayListSpliterator implements Spliterator {

        /*
         * If ArrayLists were immutable, or structurally immutable (no
         * adds, removes, etc), we could implement their spliterators
         * with Arrays.spliterator. Instead we detect as much
         * interference during traversal as practical without
         * sacrificing much performance. We rely primarily on
         * modCounts. These are not guaranteed to detect concurrency
         * violations, and are sometimes overly conservative about
         * within-thread interference, but detect enough problems to
         * be worthwhile in practice. To carry this out, we (1) lazily
         * initialize fence and expectedModCount until the latest
         * point that we need to commit to the state we are checking
         * against; thus improving precision.  (This doesn"t apply to
         * SubLists, that create spliterators with current non-lazy
         * values).  (2) We perform only a single
         * ConcurrentModificationException check at the end of forEach
         * (the most performance-sensitive method). When using forEach
         * (as opposed to iterators), we can normally only detect
         * interference after actions, not before. Further
         * CME-triggering checks apply to all other possible
         * violations of assumptions for example null or too-small
         * elementData array given its size(), that could only have
         * occurred due to interference.  This allows the inner loop
         * of forEach to run without any further checks, and
         * simplifies lambda-resolution. While this does entail a
         * number of checks, note that in the common case of
         * list.stream().forEach(a), no checks or other computation
         * occur anywhere other than inside forEach itself.  The other
         * less-often-used methods cannot take advantage of most of
         * these streamlinings.
         */

        private int index; // 當(dāng)前指數(shù),在提前/拆分時修改
        private int fence; // -1直到使用; 然后是最后一個索引
        private int expectedModCount; // 柵欄設(shè)置時初始化

        /** 創(chuàng)建覆蓋給定范圍的新分裂器. */
        ArrayListSpliterator(int origin, int fence, int expectedModCount) {
            this.index = origin;
            this.fence = fence;
            this.expectedModCount = expectedModCount;
        }

        private int getFence() { // initialize fence to size on first use
            int hi; // (a specialized variant appears in method forEach)
            if ((hi = fence) < 0) {
                expectedModCount = modCount;
                hi = fence = size;
            }
            return hi;
        }

        public ArrayListSpliterator trySplit() {//拆分
            int hi = getFence(), lo = index, mid = (lo + hi) >>> 1;
            return (lo >= mid) ? null : // divide range in half unless too small
                new ArrayListSpliterator(lo, index = mid, expectedModCount);
        }

        public boolean tryAdvance(Consumer action) {//迭代,若有下一位返回true
            if (action == null)
                throw new NullPointerException();
            int hi = getFence(), i = index;
            if (i < hi) {
                index = i + 1;
                @SuppressWarnings("unchecked") E e = (E)elementData[i];
                action.accept(e);
                if (modCount != expectedModCount)
                    throw new ConcurrentModificationException();
                return true;
            }
            return false;
        }

        public void forEachRemaining(Consumer action) {
            int i, hi, mc; // hoist accesses and checks from loop
            Object[] a;
            if (action == null)
                throw new NullPointerException();
            if ((a = elementData) != null) {
                if ((hi = fence) < 0) {
                    mc = modCount;
                    hi = size;
                }
                else
                    mc = expectedModCount;
                if ((i = index) >= 0 && (index = hi) <= a.length) {
                    for (; i < hi; ++i) {
                        @SuppressWarnings("unchecked") E e = (E) a[i];
                        action.accept(e);
                    }
                    if (modCount == mc)
                        return;
                }
            }
            throw new ConcurrentModificationException();
        }

        public long estimateSize() {
            return getFence() - index;
        }

        public int characteristics() {
            return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
        }
    }

removeIf(Predicate filter) 刪除表達(dá)式返回true的元素

 @Override
    public boolean removeIf(Predicate filter) {
        return removeIf(filter, 0, size);
    }

removeIf(Predicate filter, int i, final int end)刪除范圍呃逆,表達(dá)式返回true的元素

boolean removeIf(Predicate filter, int i, final int end) {
        Objects.requireNonNull(filter);
        int expectedModCount = modCount;
        final Object[] es = elementData;//緩沖區(qū)
        // Optimize for initial run of survivors
        for (; i < end && !filter.test(elementAt(es, i)); i++)
            ;
        // Tolerate predicates that reentrantly access the collection for
        // read (but writers still get CME), so traverse once to find
        // elements to delete, a second pass to physically expunge.
        if (i < end) {
            final int beg = i;
            final long[] deathRow = nBits(end - beg);
            deathRow[0] = 1L;   // set bit 0
            for (i = beg + 1; i < end; i++)
                if (filter.test(elementAt(es, i)))
                    setBit(deathRow, i - beg);
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            modCount++;
            int w = beg;
            for (i = beg; i < end; i++)
                if (isClear(deathRow, i - beg))
                    es[w++] = es[i];
            shiftTailOverGap(es, w, end);
            return true;
        } else {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            return false;
        }
    }

replaceAll(UnaryOperator operator)替換范圍內(nèi)元素

 @Override
    public void replaceAll(UnaryOperator operator) {
        replaceAllRange(operator, 0, size);
        modCount++;
    }

replaceAllRange(UnaryOperator operator, int i, int end)替換范圍內(nèi)元素,每個元素都替換成執(zhí)行UnaryOperator后的結(jié)果

private void replaceAllRange(UnaryOperator operator, int i, int end) {
        Objects.requireNonNull(operator);
        final int expectedModCount = modCount;
        final Object[] es = elementData;
        for (; modCount == expectedModCount && i < end; i++)
            es[i] = operator.apply(elementAt(es, i));
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
    }

sort(Comparator c)排序集合

 public void sort(Comparator c) {
        final int expectedModCount = modCount;
        Arrays.sort((E[]) elementData, 0, size, c);//調(diào)用Arrays.sort
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
        modCount++;
    }

checkInvariants() 檢查不變量

void checkInvariants() {
        // assert size >= 0;
        // assert size == elementData.length || elementData[size] == null;
    }

文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請注明本文地址:http://specialneedsforspecialkids.com/yun/74903.html

相關(guān)文章

  • java源碼

    摘要:集合源碼解析回歸基礎(chǔ),集合源碼解析系列,持續(xù)更新和源碼分析與是兩個常用的操作字符串的類。這里我們從源碼看下不同狀態(tài)都是怎么處理的。 Java 集合深入理解:ArrayList 回歸基礎(chǔ),Java 集合深入理解系列,持續(xù)更新~ JVM 源碼分析之 System.currentTimeMillis 及 nanoTime 原理詳解 JVM 源碼分析之 System.currentTimeMi...

    Freeman 評論0 收藏0
  • ArrayList源碼解讀(一)

    摘要:源碼解讀屬性默認(rèn)的初始化空間空的數(shù)組用于空對象初始化存儲數(shù)組,非私有簡化了嵌套類訪問實際存儲的數(shù)據(jù)量集合被操作次數(shù),次數(shù)對不上拋出構(gòu)造方法設(shè)置初始空間大小的構(gòu)造方法大于就構(gòu)造對應(yīng)長度的數(shù)組等于就直接賦值空的數(shù)組對象小于就拋出異常無參構(gòu)造方法 ArrayList源碼解讀 屬性 private static final int DEFAULT_CAPACITY = 10;/...

    Meils 評論0 收藏0
  • dubbo源碼解析()Dubbo擴展機制SPI

    摘要:二注解該注解為了保證在內(nèi)部調(diào)用具體實現(xiàn)的時候不是硬編碼來指定引用哪個實現(xiàn),也就是為了適配一個接口的多種實現(xiàn),這樣做符合模塊接口設(shè)計的可插拔原則,也增加了整個框架的靈活性,該注解也實現(xiàn)了擴展點自動裝配的特性。 Dubbo擴展機制SPI 前一篇文章《dubbo源碼解析(一)Hello,Dubbo》是對dubbo整個項目大體的介紹,而從這篇文章開始,我將會從源碼來解讀dubbo再各個模塊的實...

    DirtyMind 評論0 收藏0
  • React 源碼深度解讀):首次 DOM 元素渲染 - Part 2

    摘要:本文將要講解的調(diào)用棧是下面這個樣子的平臺無關(guān)相關(guān)如果看源碼,我們會留意到很多相關(guān)的代碼,我們暫時先將其忽略,會在后續(xù)的文章中進行講解。現(xiàn)在我們來看一下各實例間的關(guān)系目前為止的調(diào)用棧平臺無關(guān)相關(guān)下一篇講解三總結(jié)本文講解了轉(zhuǎn)化為的過程。 歡迎關(guān)注我的公眾號睿Talk,獲取我最新的文章:showImg(https://segmentfault.com/img/bVbmYjo); 一、前言 R...

    wean 評論0 收藏0
  • swoft| 源碼解讀系列: 啟動階段, swoft 都干了些啥?

    摘要:源碼解讀系列二啟動階段都干了些啥閱讀框架源碼了解啟動階段的那些事兒小伙伴剛接觸的時候會感覺壓力有點大更直觀的說法是難開發(fā)組是不贊成難這個說法的的代碼都是實現(xiàn)的而又是世界上最好的語言的代碼閱讀起來是很輕松的之后開發(fā)組會用系列源碼解讀文章深 date: 2018-8-01 14:22:17title: swoft| 源碼解讀系列二: 啟動階段, swoft 都干了些啥?descriptio...

    hqman 評論0 收藏0

發(fā)表評論

0條評論

最新活動
閱讀需要支付1元查看
<