[英]java check if list of object contains object with concrete name
我有对象列表:
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.