从列表中删除对象 [英] remove an object from a List

查看:217
本文介绍了从列表中删除对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个铅笔类,它有两个这样的属性:

let's say we have a a Pencil class which has two attributes like this:

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个铅笔对象放入一个方框:

then we put 4 Pencil's object into a Box:

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));
    }
}

然后我们要删除其中一个对象基于颜色的值的列表:

and then we want to remove one of these objects from the list based of the value of color:

public class TestDrive {
    public static void main(String[] args) {
        Box b = new Box();
        ArrayList box = b.list;        
        Iterator it = box.iterator();
        while(it.hasNext()) {
            Pencil p = (Pencil) it.next();
            if (p.getColor() == "black") {
                box.remove(p);
            }
        }
    }
}

似乎非常简单,但我得到线程main中的异常java.util.ConcurrentModificationException 。我很感激,如果有人能说出我在这里缺少的东西

seems pretty straightforward, but i'm getting Exception in thread "main" java.util.ConcurrentModificationException. I'd appreciate it if someone could tell what I'm missing here

推荐答案

你有两个问题。

第一个问题 - 为什么你得到 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();
        }
    }
}

这篇关于从列表中删除对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆