Search code examples
javasetlinkedhashset

Java LinkedHashSet not removing duplicates even after overriding equals and hashCode methods


I am trying to remove duplicates from a List of objects by adding all the objects in the list to a Set and adding the data back to the list. My code is as follows:

List<LocationHourListHB> locationHoursList = new ArrayList<LocationHourListHB>();
Set<LocationHourListHB> locationHoursSet = new LinkedHashSet<LocationHourListHB>();
locationHoursSet.addAll(locationHoursList);
locationHoursList.clear();
locationHoursList.addAll(locationHoursSet);

I have LocationHourListHB as follows:

public class LocationHourListHB {
    private String startTIme;
    private String endTime;

    public String getStartTIme() {
        return startTIme;
    }
    public void setStartTIme(String startTIme) {
        this.startTIme = startTIme;
    }
    public String getEndTime() {
        return endTime;
    }
    public void setEndTime(String endTime) {
        this.endTime = endTime;
    }

    @Override
    public boolean equals(Object o) {

        if (o == this) return true;
        if (!(o instanceof LocationHourDay)) {
            return false;
        }

        LocationHourListHB locationHour = (LocationHourListHB) o;

        return locationHour.startTIme.equalsIgnoreCase(startTIme) &&
                locationHour.endTime.equalsIgnoreCase(endTime);
    }

    //Idea from effective Java : Item 9
    @Override
    public int hashCode() {
        int result = 17;
        result = 31 * result + startTIme.hashCode();
        result = 31 * result + endTime.hashCode();
        return result;
    }


}

I have added the override methods to equals() and hashCode(), but my list still contains duplicates. Is there anything that I am missing here.


Solution

  • Your equals method shouldn't check:

    if (!(o instanceof LocationHourDay)) {
        return false;
    }
    

    It should check:

    if (!(o instanceof LocationHourListHB)) {
        return false;
    }
    

    Since it is comparing LocationHourListHB instances.