我有对象列表:
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() 方法而不是我的
最佳答案
看起来您的问题出在字符串比较中:
if(this.name == otherMyClass.name)
将其更改为:
if(this.name.equals(otherMyClass.name))
关于java检查对象列表是否包含具有具体名称的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26969236/