如何防止将重复对象添加到ArrayList [英] How to prevent the adding of duplicate objects to an ArrayList

查看:399
本文介绍了如何防止将重复对象添加到ArrayList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

防止数组列表中的重复条目

我有一个数组列表一个特定的类C.

I have an arraylist of a particular class C.

List<C> myList = new ArrayList<C>();

C类有两个属性,即

String str1;
String str2;

现在,当我将类型为C的对象添加到ArrayList myList时,我想检查列表中已经存在一个对象,其中str1和str2的值与要添加的对象的参数(str1和str2)的值相匹配。

Now as and when I am adding objects of type C to the ArrayList myList, I want to check if there already exists an object in the list with the values of str1 and str2 matching the values of the parameters (str1 and str2) of the object I am about to add.

有没有任何有效的方式来做,而不必每次遍历完整的列表并检查参数之间的匹配?

Is there any efficient way to do this without having to iterate everytime through the complete list and checking for matching between the parameters?

推荐答案

您需要覆盖C类中的等于方法。

You need to override the equals method in Class C.

例如

public boolean equals(Object c) {
    if(c !instanceof C) {
        return false;
    }

    C that = (C)c;
    return this.str1.equals(that.getStr1()) && this.str2.equals(that.getStr2());
}

然后你可以调用myList.contains(viz)来查看列表是否已经包含一个相等的对象。

Then you can call myList.contains(viz) to see if the list already contains an equal object.

这是未经测试的,您可能需要一些额外的错误处理。

This is untested, you may want some additional error handling.

如果你重写了这样的equals方法,你还应该确保覆盖hashcode()方法。请参阅: http://www.technofundo.com/tech/java/equalhash.html

If you do override the equals method like this, you should also make sure you override the hashcode() method. See: http://www.technofundo.com/tech/java/equalhash.html

修改
正如在评论中指出的那样,集合的实现将会更有效率,尽管如此仍然需要重写equals / hashcode方法,所以上面的例子可能最好与上面的Karthiks答案一起使用。

Edit: As pointed out in the comments, the set implementation is going to be more efficient, though you will still need to override equals / hashcode method so the above example may be best used in conjunction with Karthiks answer above.

这篇关于如何防止将重复对象添加到ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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