简体   繁体   中英

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);

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:

@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

It looks like your problem is in String comparison :

if(this.name == otherMyClass.name)

Change it to :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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