java检查对象列表是否包含具体名称的对象

mas*_*y88 3 java list equals object hashcode

我有对象列表:

List<City> cities = city.getList();
Run Code Online (Sandbox Code Playgroud)

我想删除重复项(其中重复项表示具有相同参数值name和不同(id和其他参数)的对象;

我有代码:

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

我已经为hashCode()和equals()方法写了:

@Override
public int hashCode() {
    return id.hashCode();
}
Run Code Online (Sandbox Code Playgroud)

...

  @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;
        }
    }
Run Code Online (Sandbox Code Playgroud)

但它适用它.它使用object.equals()方法而不是我的方法

Era*_*ran 5

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

if(this.name == otherMyClass.name)
Run Code Online (Sandbox Code Playgroud)

将其更改为:

if(this.name.equals(otherMyClass.name))
Run Code Online (Sandbox Code Playgroud)