【每日一篇】JAVA集合详解----ArrayList(中)

分成两篇好了

上篇


补全剩下的方法:

1.add()

    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }

    /**
     * Inserts the specified element at the specified position in this
     * list. Shifts the element currently at that position (if any) and
     * any subsequent elements to the right (adds one to their indices).
     *
     * @param index index at which the specified element is to be inserted
     * @param element element to be inserted
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public void add(int index, E element) {
        rangeCheckForAdd(index);

        ensureCapacityInternal(size + 1);  // Increments modCount!!
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        elementData[index] = element;
        size++;
    }   

        如上所示,不指定add位置时,先是调用了ensureCapacityInternal()方法拓展了内部数组elementData的大小,然后在最新的位置添加元素。

   指定位置的add()方法则首先是拓展内部数组,然后使用native方法调整元素位置,然后添加元素到指定位置,值得注意的是,这个方法和set()方法颇为相似,区别在于set方法并不会扩大数组,而是直接覆盖了指定位置的元素

   2.remove()方法,也分两个,输入int(下标)的方法没什么意思,无非就是add()方法的相反操作而已,输入object(元素)的方法则调用了fastRemove()方法,这个方法是private方法,省略了确认下标范围的动作所以fast了一点点,其他和remove方法没区别

    3.clear方法,将所有数组元素设为null,将size设为0,值得注意的是并没有改变elementData数组的结构

    4.addALL(),和add()方法差不多,反正是进来的集合转数组,然后调整大小插入的东西啦

    5.removeAll()调用Object.requireNonNull方法判断输入的集合非空,然后调用batchRemove(c,false)方法,隔壁retainAll()调用的则是batchRemove(c,true),仔细看下这个方法:

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

        实际上这个方法就是删除所有不满足输入集合及条件的元素然后改变了列表大小而已,值得注意的是并不会被集合顺序限制。

    6.writeObject()(将列表写入流,即序列化列表)、readObject(反序列化列表)

    7.迭代器iterator(),这方法关系到两个迭代器内部类:

        1,Literator:

            

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
        int expectedModCount = modCount;

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

        @Override
        @SuppressWarnings("unchecked")
        public void forEachRemaining(Consumer<? super E> 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 (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();
        }

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

        这个迭代器包含三个常量:表示光标位置的cursor,表示上一个返回元素的lastRet,表示期望修改次数的expectedModCount(任何一个操作均会检定这个值,如果其他迭代器操作导致修改次数变化,则报错,这也是fast-fail的实际实现)

实现了五个方法:查看是否有下个元素的hasNext(),获取下一个元素的next以及移除下个元素的remove,保证修改可靠的checkForComodification,以及1.8新方法,传入函数遍历所有存在元素的forEachRemaining。

    2.列表迭代器ListItr,继承了上面的Ltrator,新增previous(回退上个元素),hasPrevious()查看是否有上个元素,nextIndex,返回下个元素的下标,previousIndex返回上个元素的下标,为上个元素赋值的set以及新增元素的add这几个方法

    8.subList(),判断输入的范围值合法后生产指定范围的子列表视图,关系的到内部类SubList,这个类大的一笔,感觉都可以专门开个文章写了,因为实在太大就不贴了,大概看一遍吧

    

    

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值