避免使用ArrayList中的subList方法及详解

案列

public static void main(String[] args) {
    List<String> names = new ArrayList<String>() {{
        add("hht1");
        add("hht2");
        add("hht3");
    }};

    ArrayList subList = names.subList(0, 1);
    System.out.println(subList);
}

报错

java.lang.ClassCastException: 
java.util.ArrayList$SubList cannot be cast to java.util.ArrayList

why?

jdk注释

Returns a view of the portion of this list between the
specifiedfromIndex, inclusive, and toIndex, exclusive.

意思是他是一个视图,那我可以这样理解,他没有真正的改变,只是创建了一个视图指向了它,视图的结果就是我们想要的结果

有点绕?
public List<E> subList(int fromIndex, int toIndex) {
    subListRangeCheck(fromIndex, toIndex, size);
    return new SubList(this, 0, fromIndex, toIndex);
}

这个方法返回了一个SubList而不是ArrayList,这个类是ArrayList中的一个内部类。而不是子类,所以会

java.lang.ClassCastException: 
java.util.ArrayList$SubList cannot be cast to java.util.ArrayList
SubList(AbstractList<E> parent,
            int offset, int fromIndex, int toIndex) {
    this.parent = parent;
    this.parentOffset = fromIndex;
    this.offset = offset + fromIndex;
    this.size = toIndex - fromIndex;
    this.modCount = ArrayList.this.modCount;
}

构造函数中把原来的List以及该List中的部分属性直接赋值给自己,
SubList并没有重新创建一个List,而是直接引用了原有的List(返回了父类的视图),只是指定了一下他要使用的元素的范围而已(从fromIndex(包含),到toIndex(不包含))

SubList这个类中单独定义了set、get、size、add、remove等方法。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

orange大数据技术探索者

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值