关于ArrayList源码的一些自我理解以及解析(七):函数式接口在ArrayList中的使用

之前把ArrayList的大部分源码都阅读了一遍,接下来就一口气理解完剩下的几个方法。

    @Override
    public boolean removeIf(Predicate<? super E> filter) {
        Objects.requireNonNull(filter);
        // figure out which elements are to be removed
        // any exception thrown from the filter predicate at this stage
        // will leave the collection unmodified
        int removeCount = 0;
        final BitSet removeSet = new BitSet(size);
        final int expectedModCount = modCount;
        final int size = this.size;
        for (int i=0; modCount == expectedModCount && i < size; i++) {
            @SuppressWarnings("unchecked")
            final E element = (E) elementData[i];
            if (filter.test(element)) {
                removeSet.set(i);
                removeCount++;
            }
        }
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
        // shift surviving elements left over the spaces left by removed elements
        final boolean anyToRemove = removeCount > 0;
        if (anyToRemove) {
            final int newSize = size - removeCount;
            for (int i=0, j=0; (i < size) && (j < newSize); i++, j++) {
                i = removeSet.nextClearBit(i);
                elementData[j] = elementData[i];
            }
            for (int k=newSize; k < size; k++) {
                elementData[k] = null;  // Let gc do its work
            }
            this.size = newSize;
            if (modCount != expectedModCount) {
                throw new ConcurrentModificationException();
            }
            modCount++;
        }
        return anyToRemove;
    }
   

首先从方法名称入手,removeIf这个方法,根据返回的类型boolean来看,可以理解成“是否移除”。然后看它接收的参数,是一个名叫filter的Predicate类型的变量,Predicate是在API24中引入的一种函数式接口,和Consumer一样。

首先判断传进来的参数是否为空,然后定义removeMount来记录被移除的数量,然后建立一个BitSet类型的名叫removeSet的数据集合,然后将ArrayList的size大小传递进去,然后是确保数据是最新数据的expectedMount,然后是记录ArrayList的size大小的同名size。在所有工作都准备完毕后,开始进入for循环。

        for (int i=0; modCount == expectedModCount && i < size; i++) {
            @SuppressWarnings("unchecked")
            final E element = (E) elementData[i];
            if (filter.test(element)) {
                removeSet.set(i);
                removeCount++;
            }
        }

只有当操作到的数据是ArrayList最新的数据,for循环才会不断的执行里面代码块的代码。里面的语句也很好理解,将ArrayList的每一个元素都取出来,如果满足了传递进来的参数filter.test,则记录相对应位置的下标。removeSet.set方法是BitSet里面的一个方法,官方是这样的:

voidset(int bitIndex)

Sets the bit at the specified index to true.

设置指定索引位置的值为true,这样,removeSet里面就保存了所有符合filter条件的元素下标索引了。每有一个符合条件的元素都会使removeCount+1。

for循环下面的if是确保我记录了这些位置之后,ArrayList的数据没有发生变化,如果这边刚记录为所有的位置,突然你ArrayList里面的数据发生了改动,岂不是做了无用功夫。

        // shift surviving elements left over the spaces left by removed elements
        final boolean anyToRemove = removeCount > 0;
        if (anyToRemove) {
            final int newSize = size - removeCount;
            for (int i=0, j=0; (i < size) && (j < newSize); i++, j++) {
                i = removeSet.nextClearBit(i);
                elementData[j] = elementData[i];
            }
            for (int k=newSize; k < size; k++) {
                elementData[k] = null;  // Let gc do its work
            }
            this.size = newSize;
            if (modCount != expectedModCount) {
                throw new ConcurrentModificationException();
            }
            modCount++;
        }

 在有了存储了索引位置的BitSet后,后面的事情就很好做了,首先判断是否有符合条件的元素,也就是布尔值anyToRemove。随后定义了一个newsize,用于记录执行完操作后,里面数据的长度。

removeSet.nextClearBit方法有点像迭代器,它的返回值是整个BitSet里面从i开始遇到的第一个值为false的下标索引。官方是这样说的:

public int nextClearBit (int fromIndex)

Returns the index of the first bit that is set to false that occurs on or after the specified starting index.

 

Parameters
fromIndexint: the index to start checking from (inclusive)

 

Returns
intthe index of the next clear bit

也就是说,之前使用方法removeSet.set方法设置的下标索引不会被读取到,也就是说跳过了那些符合filter条件的元素。在for循环中,i不断的从BitSet中读取出不需要remove的索引下标,然后j不断的重新为ArrayList的elementData赋值。

举个例子,一个长度为10内容为0123456789的elementData,此时使用removeSet.set方法后,满足filter条件的索引是这些:(2,7)两个下标索引值。然后removeSet.nextClearBit不断的取出(0,1,3,4,5,6,8,9)这些下标索引值。

当for循环执行完毕后,ArrayList里面的elementData数据就变成了这样:0134568989.

这个套路十分的熟悉,就是ArrayList的移动套路,将前面的值覆盖掉之后,将后面多出来的不需要的值全部设置成为null。于是就有了这段代码:

            for (int k=newSize; k < size; k++) {
                elementData[k] = null;  // Let gc do its work
            }
            this.size = newSize;
            if (modCount != expectedModCount) {
                throw new ConcurrentModificationException();
            }
            modCount++;

 如果一个数组的末尾有连续的null,则GC回收机制会将这些null回收掉。此时再刷新ArrayList的size值,由于elementData的长度发生了改变,于是告诉modCount要+1,表示ArrayList里面的数据发生了改动。

最后代码返回anyToRemove的值,如果改动了就返回true,没有改动就返回false。

removeIf方法的作用就是,移除符合filter条件的元素。

    @Override
    @SuppressWarnings("unchecked")
    public void replaceAll(UnaryOperator<E> operator) {
        Objects.requireNonNull(operator);
        final int expectedModCount = modCount;
        final int size = this.size;
        for (int i=0; modCount == expectedModCount && i < size; i++) {
            elementData[i] = operator.apply((E) elementData[i]);
        }
        if (modCount != expectedModCount) {
            throw new ConcurrentModificationException();
        }
        modCount++;
    }

replaceAll方法,替换所有。也就是说,将符合operator条件的元素全部替换成指定的元素,而指定的元素由operator来决定。

首先,确保传递进来的参数不是空的,然后记录modCount的值,然后记录ArrayList里面数据的size。之后采用for循环,循环变化每一个elementData的值。

举个例子,假如有一个长度为7内容为0123456的数据,然后operator要求所有的数都变成7,然后替换所有的数,于是这些数据就变成了这个样子:7777777.

不过值得注意的是,此时ArrayList的modCount发生了变化。之前我们的理解并没有错,modCount是记录ArrayList里面的数据是否发生变动。在ArrayList的set方法都没有让modCount发生变化,replaceAll应该也可以理解成对所有元素都执行一遍set方法,为什么replaceAll方法就要记录modCount呢?

ArrayList自己的set方法:

    public E set(int index, E element) {
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
        E oldValue = (E) elementData[index];
        elementData[index] = element;
        return oldValue;
    }

带着疑惑,找到了与replaceAll相近的一个方法:clear方法。

    public void clear() {
        modCount++;
        // clear to let GC do its work
        for (int i = 0; i < size; i++)
            elementData[i] = null;
        size = 0;
    }

clear是清空ArrayList里面的所有数据,使其变成null。那么这就好解释为什么replaceAll也要记录modCount的变化了。因为ArrayList无法确保参数operator传递进来的不是null,也就是说replaceAll方法很有可能让所有数据都变成null。

可是,replaceAll方法的第一行不是确保了传递进来的参数非空吗?这时候我们要重新定义一下“空”这个意思。

正常情况,我们定义一个Int类型名叫number的数字,并将6赋值给它。我们可以写成一句代码:int number = 6;但是对于机器来说,它的流程是这样子的步骤:开辟一块空间保存number这个名字;再开辟一块空间存储6这个值的内容;再将number指向6这个值得地址。

那么,当只定义不赋值的时候,步骤就成了这样:开辟一块空间保存number这个名字。这个number并没有指向任何地址。这种情况在C语言中称number为空指针。这下应该就能理解“空”和“为空”。前者的“空”是不指向任何的值,而后者的“空”是内容为空,它在内存中是有一块确定的地址的。

所以。Objects.requireNonNull(operator);是为了防止operator是个空指针,并没有指向任何内容。所以使用replaceAll方法的时候会认为ArrayList的数据发生了改动。

或许还有另外一种解释,removeIf和replaceAll方法,传递的参数都是在API24中定义的函数式接口。也就是说,只要传递的参数是一个lamda表达式,那么就认为ArrayList的数据发生了一次改动。

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

sort方法,传递一个Comparator用来按指定顺序重新排序。假如,一个长度为5内容为13206的数据,此时按传递的参数Comparator要求的顺序排列(假设从小到大排序),在调用了sort方法之后,ArrayList里面的数据顺序就变成了这样:01236.

总结:

ArrayList的源码涉及到了迭代器,以及“函数式接口”这种知识点。在写的时候,也是一边查阅其他博客资料,一边自己理解的。以后觉得哪里写错了再回来更改吧。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值