util集合类SubList源码分析

SubList继承AbstractList抽象类,AbstractList实现了List接口,所以SubList说到底就是一个List的实现类。

SubList是通过subList()方法返回的对象,主要用于返回一个List集合的其中一部分视图。

SubList的构造函数:

SubList(AbstractList<E> list, int fromIndex, int toIndex) {
        if (fromIndex < 0)
            throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
        if (toIndex > list.size())
            throw new IndexOutOfBoundsException("toIndex = " + toIndex);
        if (fromIndex > toIndex)
            throw new IllegalArgumentException("fromIndex(" + fromIndex +
                                               ") > toIndex(" + toIndex + ")");
        l = list;
        offset = fromIndex;
        size = toIndex - fromIndex;
        this.modCount = l.modCount;
    }

通过构造函数中可以看出,生成SubList的时候,会把之前的List作为Parent属性,并且会把Parent的modCount作为自身的modCount。

再看List的2个比较重要的方法:

public void add(int index, E element) {
        rangeCheckForAdd(index);
        checkForComodification();
        l.add(index+offset, element);
        this.modCount = l.modCount;
        size++;
    }

    public E remove(int index) {
        rangeCheck(index);
        checkForComodification();
        E result = l.remove(index+offset);
        this.modCount = l.modCount;
        size--;
        return result;
    }

通过add和remove方法可以看出,当我们试图对SubList进行修改的时候,那么也会同时对Parent进行一样的修改。

再看add和remove都同时调用的checkForComodification方法:

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

方法里面判断SubList的modCount是否被修改过,它使用的是Parent的modCount,那么如果当Parent进行了add和remove等操作,那么SubList进行add和remove操作的时候,会抛出ConcurrentModificationException异常。

因此,对于使用SubList总结几点:

1.SubList应该仅仅作为试图使用,谨慎对他进行任何的add和remove操作,因为无法确保Parent是否有改动过

2.当SubList进行改动的时候,Parent会同时进行改动操作

3.当Parent进行改动操作之后,之前返回的SubList变得不可使用

转载于:https://my.oschina.net/u/3835212/blog/3068031

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值