subList()
是返回集合在区间[startIndex, endIndex)的元素集合
public static final void main(String[] args) {
List<String> stringList = new ArrayList(){{
add("test0");
add("test1");
add("test2");
add("test3");
add("test4");
}};
List<String> subList = stringList.subList(2,4); //[startIndex, endIndex)
System.out.println("stringList=>" + stringList);
System.out.println("subList=>" + subList);
}
输出结果
注意事项❗️
- 删除、新增原集合元素,在遍历、增加、删除子集合元素时会报系统异常
ConcurrentModificationException
。
// 省略前置代码
System.out.println("原集合添加test5");
try {
stringList.add("test5"); // 不会报错
// stringList.remove("test2")
System.out.println(subList); // 输出subList时抛出ConcurrentModificationException异常
} catch (Exception exception) {
exception.printStackTrace();
}
- 修改原集合的元素,子元素的集合也会改变
List<String> subList = stringList.subList(2,4); //[startIndex, endIndex)
System.out.println("修改原集合元素");
try {
stringList.set(3, "update->test0");
System.out.println("subList => " + subList);
} catch (Exception exception) {
exception.printStackTrace();
}
- 修改子集合的元素,会导致原集合发生改变
List<String> subList = stringList.subList(2,4); //[startIndex, endIndex)
System.out.println("修改子集合元素");
try {
subList.set(0, "updateSub->test2");
System.out.println("stringList => " + stringList);
System.out.println("subList => " + subList);
} catch (Exception exception) {
exception.printStackTrace();
}
- 子集合添加或删除元素,原集合也会发生变化。
List<String> subList = stringList.subList(2,4); //[startIndex, endIndex)
System.out.println("子集合添加/删除元素");
try {
subList.add("subAdd");
// subList.remove(0);
System.out.println("stringList => " + stringList);
System.out.println("subList => " + subList);
} catch (Exception exception) {
exception.printStackTrace();
}
原因🔍
查看subList()源码
public List<E> subList(int fromIndex, int toIndex) {
return new SubList<>(this, fromIndex, toIndex);
}
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;
}
发现new SubList<>(this, fromIndex, toIndex)构造函数并没有返回一个新的集合对象