如何将两个不同的对象放入一个 TreeSet 中?

How to get two different objects into a TreeSet?

我无法将两个不同的 objects 变成一个 TreeSet 如果一个

compareTo(the other)==0.

有人可以帮助理解这一点吗?我怎样才能在树集中实现它。

 public class Test

{
    private static SortedSet sortedSet = new TreeSet();

    public static void main(String[] args) {
        sortedSet.add(new IntegerBucket("Winner", 3));
        sortedSet.add(new IntegerBucket("Looser", 3));

        System.out.println("sortedSet has " + sortedSet.size() + " members");
        System.out.println(sortedSet);
    }

}

class IntegerBucket implements Comparable {
    private int value = 0;
    private String name = null;

    public IntegerBucket(String n, int val) {
        name = n;
        value = val;
    }

    public int getValue() {
        return value;
    }

    // Comparable interface
    public int compareTo(Object ob) {

        return getValue() - ((IntegerBucket) ob).getValue();

    }

    public String toString() {
        return name + " " + getValue();
    }
}

以上程序的输出是:

sortedSet has 1 members
[Winner 3]

你不能,根据 TreeSet class 的合同。

Note that the ordering maintained by a set (whether or not an explicit comparator is provided) must be consistent with equals if it is to correctly implement the Set interface. (See Comparable or Comparator for a precise definition of consistent with equals.)

如果您有不同的对象(即 !a.equals(b)),其中 a.compare(b)comparator.compare(a, b) 为零,则您违反了此合同。

唯一可以(间接)做到这一点的方法是在构造 TreeSet 时传入 Comparator (例如 new TreeSet<>(someComparator) 对象之间的平局,即导致compare(a, b) 的结果为非零。