如果ArrayList包含不起作用

时间:2012-06-08 06:08:44

标签: android

我正在开发具有大量ArraYlists的应用程序,它需要将它们与非列表数据进行比较。当我尝试这种方法fdata.contains(data2)时,它总是返回false。 ArayLists包含名为'favdat'的类,如下所示:`

public class favdat {
    public String product,term,note,link;
}

Data2的定义如下:favdat Data2=new favdat(); 我也试过保留所有方法,它返回大小为0的列表。 我知道有些数据是平等的。

所以问题是如何判断fdata是否包含data2

2 个答案:

答案 0 :(得分:9)

比较对象的默认实现是比较它们是否是同一个对象,因此具有完全相同属性的两个对象仍然不等于。您需要做的是覆盖 hashCode equals 方法。举个例子:

public int hashCode() {
    return product.hashCode() * 31 + term.hashCode();
}

public boolean equals(Object o) {
    if (o instanceof favdata) {
         favdata other = (favdata) o;
         return product.equals(other.product) 
             && term.equals(other.term) 
             && note.equals(other.note) 
             && link.equals(other.link);
    } else {
        return false;
    }
}

在java类中,通常以大写字母开头,因此它将是 Favdat ,并且您的代码通常更容易阅读以保持字段声明分开。

答案 1 :(得分:1)

您需要在equals(Object obj)内定义一个名为favdat的方法,以便进行对象比较。

以下是更详细的方法:

相关问题