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

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

问题描述

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

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

I have an arraylist of a particular class C.

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

C 类有两个属性,即.

Class C has two attributes viz.

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?

推荐答案

你需要重写 Class C 中的 equals 方法.

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

编辑:正如评论中所指出的,set 实现将更加高效,尽管您仍然需要覆盖 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天全站免登陆