如何利用subList方法将一个子列表从父列表中删除

本文介绍如何正确地从Java的父列表中删除子列表,并避免出现ConcurrentModificationException异常。通过使用临时列表来保存子列表的内容,然后从父列表中移除临时列表,可以有效地完成这一操作。
要想将一个子列表从其父列表中删除,可以使用java.util.List接口的subList方法和removeAll方法,见如下代码:


import java.util.ArrayList;
import java.util.List;

public class RemoveSubList {

public static void main(String[] args) {
List<Integer> test = new ArrayList<Integer>();
//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 contains elements: 1, 2
List<Integer> sub = test.subList(1, 3);

//remove sub list from test list
test.removeAll(sub); //wrong! throw exception!

//display the list again
System.out.print("the orginal list after remove sublist: ");
for (int i = 0; i < test.size(); i++) {
System.out.print(test.get(i) + " ");
}
System.out.println();
}
}

但是,运行代码却抛出异常
Exception in thread "main" java.util.ConcurrentModificationException
原因在于subList的实现原理。subList方法返回原始列表的一个子列表视图,该子列表视图的幕后仍然是原始列表,当改变返回的这个子列表时,父列表也同时发生改变。test.removeAll(sub);这行代码欲修改原始列表,其实无论是增加、删除还是更改其中的元素,子列表视图都会失效,所以报ConcurrentModificationException异常。
解决方法之一是将sub列表中的内容复制到一个临时列表中,再从test列表中删除这个临时列表。

//use temp list
List<Integer> temp = new ArrayList<Integer>();
for (int i = 0; i < sub.size(); i++) {
temp.add(sub.get(i));
}
//remove temp list from test list
test.removeAll(temp);

运行结果:
the orginal list: 0 1 2 3 4
the orginal list after remove sublist: 0 3 4
// AbstractList 的子类,表示父 List 的一部分 class SubList<E> extends AbstractList<E> { private final AbstractList<E> l; private final int offset; private int size; //构造参数: //list :父 List //fromIndex : 从父 List 中开始的位置 //toIndex : 在父 List 中哪里结束 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; //和父类使用同一个 modCount this.modCount = l.modCount; } //使用父类的 set() public E set(int index, E element) { rangeCheck(index); checkForComodification(); return l.set(index+offset, element); } //使用父类的 get() public E get(int index) { rangeCheck(index); checkForComodification(); return l.get(index+offset); } //子 List 的大小 public int size() { checkForComodification(); return size; } public void add(int index, E element) { rangeCheckForAdd(index); checkForComodification(); //根据子 List 开始的位置,加上偏移量,直接在父 List 上进行添加 l.add(index+offset, element); this.modCount = l.modCount; size++; } public E remove(int index) { rangeCheck(index); checkForComodification(); //根据子 List 开始的位置,加上偏移量,直接在父 List 上进行删除 E result = l.remove(index+offset); this.modCount = l.modCount; size--; return result; } protected void removeRange(int fromIndex, int toIndex) { checkForComodification(); //调用父类的 局部删除 l.removeRange(fromIndex+offset, toIndex+offset); this.modCount = l.modCount; size -= (toIndex-fromIndex); } public boolean addAll(Collection<? extends E> c) { return addAll(size, c); } public boolean addAll(int index, Collection<? extends E> c) { rangeCheck
03-20
### Java 中双重列表的实现或用法 在 Java 中,“双重列表”通常指的是嵌套的 `List` 数据结构,即一个 `List` 的元素本身也是一个 `List`。这种数据结构可以用来表示二维数组或其他复杂的分层关系。 以下是关于如何在 Java 中创建和操作双重列表的具体方法: #### 创建双重列表 可以通过嵌套的方式定义一个 `List<List<T>>` 来实现双重列表的功能。下面是一个简单的例子来展示其初始化方式[^1]: ```java import java.util.ArrayList; import java.util.List; public class DoubleListExample { public static void main(String[] args) { List<List<Integer>> doubleList = new ArrayList<>(); // 初始化子列表 List<Integer> sublist1 = new ArrayList<>(); sublist1.add(1); sublist1.add(2); List<Integer> sublist2 = new ArrayList<>(); sublist2.add(3); sublist2.add(4); // 将子列表添加到父列表中 doubleList.add(sublist1); doubleList.add(sublist2); System.out.println(doubleList); // 输出 [[1, 2], [3, 4]] } } ``` 这段代码展示了如何构建一个包含多个子列表的双重列表,并打印出它的内容。 #### 遍历双重列表 对于双重列表的操作,比如遍历其中的所有元素,可以采用两重循环的方式来完成。以下是一段用于遍历上述双重列表的例子[^3]: ```java for (List<Integer> innerList : doubleList) { for (Integer element : innerList) { System.out.print(element + " "); } System.out.println(); } // 输出: // 1 2 // 3 4 ``` 此代码片段实现了逐级访问双重列表中的每一个整数值,并将其逐一打印出来。 #### 修改双重列表的内容 修改双重列表中的某个具体位置上的值也是可行的。例如要更改第一个子列表的第一个元素为新的值: ```java if (!doubleList.isEmpty()) { List<Integer> firstSublist = doubleList.get(0); if (!firstSublist.isEmpty()) { firstSublist.set(0, 99); } } System.out.println(doubleList); // 输出 [[99, 2], [3, 4]] ``` 这里演示了定位并更新指定索引处的数据项的过程。 #### 删除子列表或者单个元素 当需要从双重列表里移除整个子列表或是某一部分时,则可调用相应的删除函数。如下所示是如何执行这些动作的一个实例: ```java // 移除第二个子列表 if (doubleList.size() >= 2) { doubleList.remove(1); } // 或者只移除第一个子列表里的首个项目 if (!doubleList.isEmpty()) { List<Integer> remainingSublist = doubleList.get(0); if (!remainingSublist.isEmpty()) { remainingSublist.remove(0); } } System.out.println(doubleList); // 如果之前已设置过则可能显示[[2]] ``` 以上部分涵盖了基本的增删改查功能应用至双重列表上的情景说明。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值