public static void main(String[] args) {
List<String> allElements = List.of("a","b","c","d","e","f");
List<String> allList = new ArrayList<>(allElements);
List<String> subList=allList.subList(1,3);
System.out.println(subList);
subList.set(0,"sub");
subList.set(1,"ssst");
System.out.println(subList);
System.out.println(allList);
}
输出是:
[b, c]
[sub, ssst]
[a, sub, ssst, d, e, f]
也就是说这里相当于取了原数组的一部分,并且对截取部分的修改会影响到原部分
subList()
方法,参数分别为
- 截取元素的起始位置,包含
- 截取元素的结束位置,不包含
那么这里跟List.of()
有没有关系?没有,这只是初始化数组元素的一种方法
如果想要不影响原数组,需要这么做:
List<String> newList = new ArrayList<>(allList.subList(1,3));
newList.set(0,"newString");
System.out.println(allList);
标签:代码,List,subList,allList,System,阅读,println,out
From: https://www.cnblogs.com/yaocy/p/16727964.html