Java中ArrayList和SubList的坑怎么解决
代码复现不要,思考一下会打印出什么?Listlist1=newArrayList(Arrays.asList("username","passwd"));Listlist2=list1.subList(0,2);list2.add("email");System.out.println(list1);System.out.println(list2);执行结果:你是否感觉疑惑?在想为什么在list2添加的在list1也添加是吧?源码解析subList接口ListsubList(intfromIndex,i
代码复现
不要,思考一下会打印出什么?
Listlist1 = new ArrayList<>(Arrays.asList("username", "passwd")); List list2 = list1.subList(0, 2); list2.add("email"); System.out.println(list1); System.out.println(list2);
执行结果:

你是否感觉疑惑?在想为什么在list2添加的在list1也添加是吧?
源码解析
subList接口
ListsubList(int fromIndex, int toIndex);
我们使用的是ArrayList,所以是选择ArrayList即可
public ListsubList(int fromIndex, int toIndex) { subListRangeCheck(fromIndex, toIndex, size); return new SubList(this, 0, fromIndex, toIndex); }
fromIndex是从List元素开始索引,toIndex是List元素结束索引,subListRangeCheck方法是检查是否在允许范围之内。
static void subListRangeCheck(int fromIndex, int toIndex, int size) {
//开始索引小于0
if (fromIndex < 0)
throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
//结束索引大于容量
if (toIndex > size)
throw new IndexOutOfBoundsException("toIndex = " + toIndex);
//开始索引大于结束索引
if (fromIndex > toIndex)
throw new IllegalArgumentException("fromIndex(" + fromIndex +
") > toIndex(" + toIndex + ")");重头戏在new SubList(this, 0, fromIndex, toIndex);这里,看看下面的SubList就会知道,this关键字将当前对象的引用也就是list1传入了SubList,把传入的list1变成parent赋值给SubList内部成员,然后又将这个构造生成的赋值给list2,也就是说list1和list2是引用了同一个对象,指向的是同一list。
SubList(AbstractListparent, 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; }
再来看看list2.add的源码,将元素直接添加在list1和list2共同的list引用对象上,这就是为什么list2添加了,list1也添加了。
public void add(int index, E e) {
rangeCheckForAdd(index);
checkForComodification();
//将元素直接添加在list1和list2共同的list引用对象上
parent.add(parentOffset + index, e);
this.modCount = parent.modCount;
this.size++;
}附:ArrayList的subList简单介绍和使用
subList(int fromIndex, int toIndex);
它返回原来list的从[fromIndex, toIndex)之间这一部分其实就是list的子列表(注意:fromIndex是 [ 说明包括其本身,toIndex是 )说明不包括其本身)。
这个子列表的本质其实还是原列表的一部分;也就是说,修改这个子列表,将导致原列表也发生改变。
举例说明
list中包含1,2,3,4,5,6一共6个元素,list.subList(1,3)返回的是2,3(list以0为开始)
还有一个经常使用的list.subList(1,list.size)
list中包含1,2,3,4,5,6一共6个元素,list.subList(1,list.size)返回的是2,3,4,5,6(list以0为开始)
Windows 10 是一款微软推出的经典操作系统,拥有硬件兼容性与多任务处理能力。它更偏向把系统状态查看和常用调节动作放在一起,适合需要持续观察和微调设备状态的场景。
极度公式是一款跨平台专业LaTeX公式识别编辑软件,支持OCR公式识别和多平台编辑。和使用说明,避免使用,享受完整功能与稳定支持。做扫描整理、文字提取和表格转换时,它能把识别后的处理步骤接得更顺,资料录入这类场景会省下不少时间。
















