JDK中,List接口有一个实例方法List
其作用是返回一个以fromIndex为起始索引(包含),以toIndex为终止索引(不包含)的子列表(List)。
但值得注意的是,返回的这个子列表的幕后其实还是原列表;
也就是说,修改这个子列表,将导致原列表也发生改变;反之 父的list改变会影响子的list失效,报错
public static void main(String[] args) {
List list = new ArrayList<>();
list.add("a");
System.out.println(list.size());
List list1 = new ArrayList<>(list);
System.out.println(list1.size());
List list2 = list.subList(0, list.size());
list2.add("b");
System.out.println(list2.size());
System.out.println(list.size());
System.out.println(list.equals(list1));
System.out.println(list.equals(list2));
list.add("c");
System.out.println(list.size());
System.out.println(list2.size());
System.out.println(list.equals(list1));
System.out.println(list.equals(list2));
}
打印结果当父list改变时候子list却是报错了
1
1
2
2
false
true
3
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$SubList.checkForComodification(ArrayList.java:1231)
at java.util.ArrayList$SubList.size(ArrayList.java:1040)
at top.coolook.contentgather.aaa.A.main(A.java:24)
下面是一段实例代码:
- import java.util.ArrayList;
- import java.util.List;
- public class TestSubList {
- public static void main(String[] args) {
- List
test = new ArrayList (); - //init list
- for (int i = 0; i < 5; i++) {
- test.add(i); //auto boxing
- }
- //display the list
- System.out.print("the orginal list: ");
- for (int i = 0; i < test.size(); i++) {
- System.out.print(test.get(i) + " ");
- }
- System.out.println();
- //sub list
- List
sub = test.subList(1, 3); //sub list contains elements: 1, 2 - sub.remove(1); //remove element “2” from sub list
- //display the list again
- System.out.print("the orginal list after sublist modified: ");
- for (int i = 0; i < test.size(); i++) {
- System.out.print(test.get(i) + " ");
- }
- System.out.println();
- }
- }
程序运行结果:
the orginal list: 0 1 2 3 4
the orginal list after sublist modified: 0 1 3 4
在这段代码中,我们并没有改变原始列表“test”其中的元素。然而,当删除由subList方法得到的子列表中的元素时,原始列表中的该元素也被删除了。
public static void main(String[] args) {
List
for(int i=0;i<5;i++){
list.add(i);
}
System.out.println(list);
List
list01.add(6);
System.out.println(list01);
System.out.println(list.toString());
System.out.println(list);
}
结果:
[0, 1, 2, 3, 4]
[1, 2, 3, 6]
[0, 1, 2, 3, 6, 4]
[0, 1, 2, 3, 6, 4]