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

标签 java set linkedhashset

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

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 实例。

关于Java LinkedHashSet 即使在覆盖 equals 和 hashCode 方法后也不会删除重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53817841/

相关文章:

algorithm - 维护一组最小的子集

java - LinkedHashSet javadoc 中的错误?

java - hibernate 是否保留 LinkedHashSet 的顺序,如果是,如何保留?

java - 当我使用 @IdClass LinkedHashSet 时包含重复的项目

java - 如何根据数组中的项目填充矩形?

java - 如何在 Java 中将 LinkedHashSet 转换为 EnumSet?

java - 关于字符串连接行为

algorithm - 分区问题蛮力算法

java - 发送收到的 spring FilePart 而不保存

OC4J 中的 java.lang.NoSuchMethodError : javax. persistence.OneToMany.orphanRemoval()Z