【发布时间】:2021-08-15 11:55:28
【问题描述】:
我有一份动物清单。我的目标是只从列表中删除狗。该怎么做?
我有以下相同的代码
Dog d1= new Dog("Dog 1");
Dog d2= new Dog("Dog 2");
Dog d3= new Dog("Dog 3");
Cat c1= new Cat("Cat 1");
Cat c2= new Cat("Cat 2");
List<Animal> al= Arrays.asList(d1,d2,c1,c2,d3);
for(Animal eachlist : al)
{
if(eachlist instanceof Dog)
{
al.remove(eachlist);
}
System.out.println(eachlist.toString());
}
积分
1.我期待 al.remove() 抛出 ConcurrentModificationException,但它会抛出 UnsoppertedException。为什么? 2. 如何真正从列表中删除所有狗
【问题讨论】:
-
为什么不期待
RuntimeException,比如你会以动态的方式做些什么?可能没什么.. -
@PradeepSimha 不,这不能回答我的问题。我的问题不是要避免 ConcurrentModificationException。我的问题是为什么我没有得到 ConcurrentModificationException(我在我的代码中期待这个异常)但是我得到了 unsopportedRuntimeException
-
你最后一个问题的答案是:你做不到。在第一个 duplink 中进行了解释。您不能在固定长度列表中添加或删除元素。
标签: java list arraylist collections concurrentmodification