List 中subList 慎用(减法陷阱)

查找java原代码我们可以看到:tempList的subList实现代码在AbstractList类里边,然而无论如何,最终 的结果都是返回一个AbstractList的子类:SubList(该类是一个使用默认修饰符修饰的类,其源代码位于 AbstractList.java类文件里边),

SubList类的构造方法:
SubList(AbstractList 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;
expectedModCount = l.modCount;
}

上面的解释通俗的讲就是,将原来的list赋值给了l,随后将游标移动。所以这两个变量的指向是同一个地址,当我们修改l的值,也就修改了指向的那个地址的值,原来的list值就发生了变化。

我们用一个测试类来测试下:
List list = new ArrayList();
for(int i = 0; i<10 ;i++){
list.add(i);
}
System.out.println(list);
List tempList = list.subList(0, 4);
System.out.println(tempList);
tempList.clear();
for(int i = 1; i<5 ;i++){
tempList.add(i);
}
System.out.println(tempList);
System.out.println(list);
测试结果为:
测试结果
地址图解释:
地址描述
这就说明了一个问题,以后慎用sublist。

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值