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

要想将一个子列表从其父列表中删除,可以使用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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值