简体   繁体   English

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

[英]java check if list of object contains object with concrete name

I have list of objects: 我有对象列表:

List<City> cities = city.getList();

I would like to remove duplicates (where duplicates mean objects with the same value of parameter name and different ( id , and other parameters); 我想删除重复项(其中重复项表示具有相同参数name和不同( id和其他参数)值的对象;

I have code for that: 我有代码:

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

I've wrote for that hashCode() and equals() method: 我已经为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;
        }
    }

But it dosnt apply it. 但它适用它。 It use object.equals() method instead of mine 它使用object.equals()方法而不是我的方法

It looks like your problem is in String comparison : 看起来您的问题在于字符串比较:

if(this.name == otherMyClass.name)

Change it to : 将其更改为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM