Java如何判断对象列表中是否包含指定名称的对象?

3
我有一个对象列表:
List<City> cities = city.getList();

我希望能够去除重复项(所谓重复项是指具有相同参数name值但不同的id和其他参数的对象)。

我已经编写了相关代码:

for(City c: cities) {
    System.out.println("analise " + c.name);
    if(!temp.contains(c)) {
        temp.add(c);
    }
}

我已经编写了hashCode()和equals()方法:
@Override
public int hashCode() {
    return id.hashCode();
}

...

  @Override
    public boolean equals(Object other) {
        if (other == null) return false;
        if (other == this) return true;
        if (!(other instanceof GenericDictionary))return false;
        GenericDictionary otherMyClass = (GenericDictionary) other;
        if(this.name == otherMyClass.name) {
            return true;
        } else {
            return false;
        }
    }

但它没有应用它,而是使用了object.equals()方法而非我的方法。

你不需要为ArrayList覆盖hashCode方法。 - Deepu--Java
1个回答

4

看起来你的问题在于字符串比较:

if(this.name == otherMyClass.name)

将其更改为:

if(this.name.equals(otherMyClass.name))

1
return name.equals(otherMyClass.name); - vikingsteve
可以了,谢谢。现在我看到了字符串比较的错误 :D - masterdany88

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接