Java 从列表中删除对象

Java 从列表中删除对象,java,list,iterator,Java,List,Iterator,假设我们有一个Pencil类,它有两个属性,如下所示: public class Pencil { String color; int length; public Pencil(String c, int sh, int l) { this.color = c; this.length = l; } public String getColor() { return color; } } 然后我

假设我们有一个Pencil类,它有两个属性,如下所示:

public class Pencil {
    String color;
    int length;

    public Pencil(String c, int sh, int l) {
        this.color = c;
        this.length = l;
    }
    public String getColor() {
        return color;
    }
}
然后我们将4支铅笔的物体放入一个盒子:

public class Box {

    ArrayList<Pencil> list;
    public Box() {
        list = new ArrayList<Pencil>();
        list.add(new Pencil("blue", 5, 10));
        list.add(new Pencil("black", 5, 10));
        list.add(new Pencil("brown", 5, 10));
        list.add(new Pencil("orange", 5, 10));
    }
}
看起来很简单,但我在线程“main”java.util.ConcurrentModificationException中得到了
异常。如果有人能告诉我这里缺少什么,我将不胜感激。调用
it.remove()
而不是
box.remove(p)
调用
it.remove()
而不是
box.remove(p)
你有两个问题

第一个问题-为什么会出现
ConcurrentModificationException
-是因为您使用列表来删除元素,而不是迭代器

必须使用
it.remove()
删除当前所在的元素

接下来,您要将字符串与
==
进行比较-这根本不能保证有效。您应该改用
.equals

将它们进行比较的顺序颠倒过来,这样就不会在那里运行得到
NullPointerException
的机会

这是这个街区的样子,再看一遍

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();
        }
    }
}
publicstaticvoidmain(字符串[]args){
框b=新框();
ArrayList box=b.list;
for(Iterator it=box.Iterator();it.hasNext();){
铅笔p=it.next();
if(“black”.equals(p.getColor())){
it.remove();
}
}
}
您有两个问题

第一个问题-为什么会出现
ConcurrentModificationException
-是因为您使用列表来删除元素,而不是迭代器

必须使用
it.remove()
删除当前所在的元素

接下来,您要将字符串与
==
进行比较-这根本不能保证有效。您应该改用
.equals

将它们进行比较的顺序颠倒过来,这样就不会在那里运行得到
NullPointerException
的机会

这是这个街区的样子,再看一遍

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();
        }
    }
}
publicstaticvoidmain(字符串[]args){
框b=新框();
ArrayList box=b.list;
for(Iterator it=box.Iterator();it.hasNext();){
铅笔p=it.next();
if(“black”.equals(p.getColor())){
it.remove();
}
}
}

这里有一些问题……为了避免任何潜在的重复关闭者,它似乎不适合“比较字符串”或“并发修改”问题。请看:@chrylis:链接副本中提出的问题与此处提出的问题性质不同。我不觉得这是一个重复的问题。@Makoto:不同意。这是关于CME来自于在
while
循环中使用
box.remove()
。@chrylis再看一眼;问题是为什么你在一个实例中得到了CME,而在另一个实例中没有。本文仅在一个上下文中询问CME(还有其他问题)。这不是一个干净的副本。这里有一些问题……为了避免任何潜在的副本关闭者,它不适合“比较字符串”或“并发修改”问题。请看:@chrylis:链接副本中提出的问题与这里提出的问题性质不同。我不觉得这是一个重复的问题。@Makoto:不同意。这是关于CME来自于在
while
循环中使用
box.remove()
。@chrylis再看一眼;问题是为什么你在一个实例中得到了CME,而在另一个实例中没有。本文仅在一个上下文中询问CME(还有其他问题)。这不是一个干净的复制品。