Java LinkedHashSet 即使在覆盖 equals 和 hashCode 方法后也没有删除重复项

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

我试图通过将列表中的所有对象添加到集合并将数据添加回列表来从对象列表中删除重复项。我的代码如下:

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

我有LocationHourListHB如下:

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


}

我已将覆盖方法添加到 equals() 和 hashCode(),但我的列表仍然包含重复项。我在这里遗漏了什么吗?

您的 equals 方法不应检查:

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

它应该检查:

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

因为它正在比较 LocationHourListHB 个实例。