繁体   English   中英

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM