更新时间:2023-12-04 20:22:52
你有两个问题。
第一个问题 - 为什么你得到 ConcurrentModificationException
- 是因为你正在使用列表删除元素,而不是迭代器。
The first issue - why you're getting ConcurrentModificationException
- is because you're using the list to remove elements, not the iterator.
您必须使用 it.remove()
删除您当前所在的元素。
You must use it.remove()
to remove the element you're currently on.
接下来,您要将字符串与 ==
进行比较 - 这根本不能保证。您应该使用 .equals
。
Next, you're comparing strings with ==
- this isn't guaranteed to work at all. You should be using .equals
instead.
反转您比较它们的顺序,这样您就不会运行也有机会获得 NullPointerException
。
Reverse the order you compare them against so you don't run a chance of getting a NullPointerException
there, too.
以下是块的外观,重新访问。
Here's what the block looks like, revisited.
public static void main(String[] args) {
Box b = new Box();
ArrayList<Pencil> box = b.list;
for(Iterator<Pencil> it = box.iterator(); it.hasNext();) {
Pencil p = it.next();
if ("black".equals(p.getColor())) {
it.remove();
}
}
}