gpt4 book ai didi

java - SortedSet - 排序和相等性测试未按预期工作

转载 作者:行者123 更新时间:2023-11-30 07:21:48 27 4
gpt4 key购买 nike

我有一个类的实例,我想按特定顺序对其进行排序,但也能够使用不同的标准判断一个实例是否存在于集合中。示例:

public class Foo {
int x;
int y;

public Foo(int x, int y) { this.x = x; this.y = y }

// equality determined by value of 'x':
@Override
public boolean equals(Object obj) {
if (obj instanceof Foo) {
return ((Foo)obj).x == this.x;
}
return false;
}

@Override
public int hashCode() {
return this.x;
}

@Override
public int compareTo(Foo foo) {
if (this.x < foo.x return -1;
else if (this.x > foo.x return 1;
return 0;
}
}

...

// Would like to keep a set of Foos, but sorted by 'y' value.
// Passing in an explicit comparator which sorts on 'y'.
SortedSet<Foo> test = new TreeSet<Foo>(new ComparatorFoo());

public static class ComparatorFoo implements Comparator<Foo> {
@Override
public int compare(Foo o1, Foo o2) {
if (o1.y < o2.y) return -1;
else if (o1.y > o2.y) return 1;
return 0;
}
}

现在尝试:

test.add(new Foo(3, 4));
test.add(new Foo(1, 2));
test.add(new Foo(5, 6));

// sorts by 'y' ok.
for (Foo foo : test) {
System.out.println(foo.toString());
}

// but can't find an instance with the same 'x' value:
test.contains(new Foo(1, 999));

我是否需要保留两个单独的数据结构来执行此操作? (一个用于排序,一个用于相等测试?)

谢谢

------更新--------

最终结果:用于初始化 SortedSet 的比较器也会在调用 contains() 时使用。因此,我无法让集合按“y”排序,并按“x”检查元素是否存在。

最佳答案

你应该定义你的 compareToequals 一致

来自 SortedSet 的 Java 文档检查突出显示的部分。

Note that the ordering maintained by a sorted set (whether or not an explicit comparator is provided) must be consistent with equals if the sorted set is to correctly implement the Set interface. (See the Comparable interface or Comparator interface for a precise definition of consistent with equals.) This is so because the Set interface is defined in terms of the equals operation, but a sorted set performs all element comparisons using its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the sorted set, equal. The behavior of a sorted set is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Set interface.

像下面这样改变你的比较器

public static class ComparatorFoo implements Comparator<Foo> {
@Override
public int compare(Foo o1, Foo o2) {
if (o1.x < o2.x)
return -1;
else if (o1.x > o2.x)
return 1;
return 0;
}
}

它将返回给你 true

关于java - SortedSet - 排序和相等性测试未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13144922/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com