JDK之ArrayList源码解读(三)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_32523587/article/details/85932421

目录

 

removeAll(Collection c)

class Itr

class ListItr

sort(Comparator c)


removeAll(Collection<?> c)

public boolean removeAll(Collection<?> c) {
        Objects.requireNonNull(c);
        return batchRemove(c, false);
    }

作用:从ArrayList里删除存在于Collection c中的所有元素。

先确保Collection c不为null,如果为null,抛出空指针异常。然后调用batchRemove(c, false)

private boolean batchRemove(Collection<?> c, boolean complement) {
        final Object[] elementData = this.elementData;
        int r = 0, w = 0;
        boolean modified = false;
        try {
            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.
            if (r != size) {
                System.arraycopy(elementData, r,
                                 elementData, w,
                                 size - r);
                w += size - r;
            }
            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;
    }

判断输入的Collection当中的数据是否和elementData当中的相等,因为complement为false,即Collection c中的值和ArrayList中的值不相等,就将结果还是放入ArrayList,这样就过滤掉了相等的部分,相当于删除操作。finally模块中,中途出现了异常,r为出错时elementData正在遍历的位置,w为遍历后结果存储的位置。出错过后,将出错后没有遍历的数据直接添加到结果的后面输出出来。

class Itr

private class Itr implements Iterator<E> {
        int cursor;       
        int lastRet = -1; 
        int expectedModCount = modCount;

        public boolean hasNext() {
        }

        @SuppressWarnings("unchecked")
        public E next() {}

        public void remove() { }

        @Override
        @SuppressWarnings("unchecked")
        public void forEachRemaining(Consumer<? super E> consumer) {}

        final void checkForComodification() {}
    }

作用:实现了Iterator接口,重写next、hasNext等接口。

cursor表示当前元素的位置,lastRet表示上一个元素的位置。

扫描二维码关注公众号,回复: 4895895 查看本文章
public boolean hasNext() {
            return cursor != size;
        }

如果当前元素的位置在ArrayList的末尾,说明迭代器已经遍历到末尾了,hasNext()返回false。

@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];
        }

当当前元素的位置超出了ArrayList的范围,抛出元素不存在的异常;当当前元素的位置超出了ArrayList中数组的范围,抛出

ConcurrentModificationException异常。否则返回数组在cursor位置的值,同时cursor和lastRet都指向数组的下一位。

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();
            }
        }

当lastRet(上一个元素的位置)小于0,抛出异常;调用ArrayList的remove()方法删除当前元素,同时cursor和lastRet都指向数组的上一位。

class ListItr

private class ListItr extends Itr implements ListIterator<E> {
        ListItr(int index) {
            super();
            cursor = index;
        }

        public boolean hasPrevious() {}

        public int nextIndex() {}

        public int previousIndex() {}

        @SuppressWarnings("unchecked")
        public E previous() {}

        public void set(E e) {}

        public void add(E e) {}
    }

该类继承了Itr,并扩展了它的功能,添加了是否有上一个元素的判断、获取上一个元素的位置、修改某一个位置的值等方法。

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

作用:判断迭代器的是否有前一个元素。

如果cursor(当前元素的位置)的值不为0,说明迭代器不是指向第一个元素,存在上一个元素。

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

作用:获取迭代器前一个元素的位置。

上一个元素的位置等于当前位置-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];
        }

作用:获取迭代器前一个元素的值。

先获取上一个元素的位置。当上一个元素的位置小于0,抛出元素不存在异常;当上一个元素的位置大于数组长度,也抛出异常。否则返回数组在cursor上一个元素位置的值,同时cursor指向数组的前一位。

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

            try {
                ArrayList.this.set(lastRet, e);
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

作用:设置迭代器前一个元素的值。

上一个元素的位置小于0,抛出状态不合法异常;调用set(int index, E element)方法,设置迭代器前一个元素的值。

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();
            }
        }

作用:在迭代器指向的位置添加元素。

sort(Comparator<? super E> c)

@Override
    @SuppressWarnings("unchecked")
    public void sort(Comparator<? super E> c) {
        final int expectedModCount = modCount;
        Arrays.sort((E[]) elementData, 0, size, c);
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
        modCount++;
    }

作用:将ArrayList里的元素按照Comparator c实现的比较大小规则进行排序。

调用Arrays.sort()方法,将数组里从第一个位置到ArrayList里最后一个元素的位置,按照Comparator c的规则进行排序。

public static <T> void sort(T[] a, int fromIndex, int toIndex,
                                Comparator<? super T> c) {
        if (c == null) {
            sort(a, fromIndex, toIndex);
        } else {
            rangeCheck(a.length, fromIndex, toIndex);
            if (LegacyMergeSort.userRequested)
                legacyMergeSort(a, fromIndex, toIndex, c);
            else
                TimSort.sort(a, fromIndex, toIndex, c, null, 0, 0);
        }
    }

当Comparator c为null,即排序规则为空时,调用sort(a, fromIndex, toIndex)。

public static void sort(Object[] a, int fromIndex, int toIndex) {
        rangeCheck(a.length, fromIndex, toIndex);
        if (LegacyMergeSort.userRequested)
            legacyMergeSort(a, fromIndex, toIndex);
        else
            ComparableTimSort.sort(a, fromIndex, toIndex, null, 0, 0);
    }

先检查起始位置与终止位置是否合法

private static void rangeCheck(int arrayLength, int fromIndex, int toIndex) {
        if (fromIndex > toIndex) {
            throw new IllegalArgumentException(
                    "fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")");
        }
        if (fromIndex < 0) {
            throw new ArrayIndexOutOfBoundsException(fromIndex);
        }
        if (toIndex > arrayLength) {
            throw new ArrayIndexOutOfBoundsException(toIndex);
        }
    }

初始位置不能大于终止位置,不能小于0,终止位置不能大于数组长度

当用户请求归并排序时,调用归并排序方法:

private static void legacyMergeSort(Object[] a,
                                        int fromIndex, int toIndex) {
        Object[] aux = copyOfRange(a, fromIndex, toIndex);
        mergeSort(aux, a, fromIndex, toIndex, -fromIndex);
    }

否则,是用另一种排序方法。

如果之前的Comparator c不为null,则根据Comparator c指定的规则进行排序。

猜你喜欢

转载自blog.csdn.net/qq_32523587/article/details/85932421