【发布时间】:2021-11-01 01:28:47
【问题描述】:
我正在处理我的项目,需要重写 tostring、equals 和 hashcode 方法。但是在这样做之后,对象中的值没有被迭代,没有被正确搜索,我怀疑这些方法只存在问题。请查看下面的课程并帮助找出这些方法之间的合同中可能存在的问题。
public class Range implements Comparable<Range> {
private BigDecimal first;
private BigDecimal last;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Range range = (Range) o;
return Objects.equals(first, range.first) &&
Objects.equals(last, range.last);
}
@Override
public int hashCode() {
return Objects.hash(first, last);
}
@Override
public int compareTo(Range r) {
int value = 0;
if (first.compareTo(r.last) > 0) {
value = -1;
} else if (last.compareTo(r.first) < 0) {
value = 1;
}
return value;
}
}
失败的地方是当我得到值时,类对象被保存为映射键并且值是字符串,而不是缺少值存在检查返回 true。
私有地图
【问题讨论】:
-
Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. 见:How to create a Minimal, Reproducible Example。
-
等式实现很好,但
compareTo实现违反了传递性要求。当它为a和b以及b和c返回零时,那么它也必须返回零以比较a和c。 -
@Holger 你能建议代码更改吗
-
没有简单的代码更改。您不能创建允许您以这种方式处理重叠范围的
compareTo方法。合同需要总订单。由于范围根本没有自然顺序,所以不要实现compareTo方法。您可以创建不同的Comparators,例如一个作为起点,一个作为终点。当集合没有重叠范围时,搜索低于或等于搜索词的最高起点就足够了。否则,您必须进行多次搜索才能找到子集。
标签: java object collections equals