javaequalshashcodehashsetjava-collections-api

How to override hashcode and equals method to avoid adding duplicate strings in HashSet in java?


In my code I have a set of PlacesInfo object ie.,

 Set<PlacesInfo> placeId;    

In this set I am adding placeId (String). I need to avoid adding duplicates to my HashSet. Here is my override method below. but, still it is adding duplicate elements to my set. So, how to avoid this?

@Override
public int hashCode() {
    int hash = 5;
    hash = 97 * hash + Objects.hashCode(this.placeId);
    return hash;
}

@Override
public boolean equals(Object obj) {
    if (obj == null) {
        return true;
    }
    if (this.getClass() != obj.getClass()) {
        return false;
    }
    final PlacesInfo other = (PlacesInfo) obj;
    if (!Objects.equals(this.placeId, other.placeId)) {
        return false;
    }
    return true;
}

Solution

  • Try this

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((placeId == null) ? 0 : placeId.hashCode());
        return result;
    }
    
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        PlacesInfo other = (PlacesInfo) obj;
        if (placeId == null) {
            if (other.placeId != null)
                return false;
        } else if (!placeId.equals(other.placeId))
            return false;
        return true;
    }