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

时间:2018-12-17 15:03:23

标签: java set linkedhashset

我试图通过将列表中的所有对象添加到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()中,但是我的列表仍然包含重复项。我在这里有什么想念的吗?

1 个答案:

答案 0 :(得分:4)

您的equals方法不应检查:

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

它应该检查:

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

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