Java check if list of objects contains object with specific name

I have a list of objects:

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

      

I would like to remove duplicates (where duplicates mean objects with the same parameter value name

and different ( id

and different parameters);

I have a code for this:

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

      

I wrote for the 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 that doesn't apply. It uses object.equals () method instead of mine

+3


source to share


1 answer


It looks like your problem is string comparison:

if(this.name == otherMyClass.name)

      



Change it to:

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

      

+5


source







All Articles