java - 比较树集是否相等

标签 java collections treeset

我有两套HashSet我转换为 TreeSet对其进行排序以便于比较。转换后HashSetTreeSet 。当我使用“等于”函数比较这两个 TreeSet 时,它说它们是不同的。我调试它,但它以相同的顺序显示相同的内容。我不明白出了什么问题?

   public class TestProductBundle {
    @SuppressWarnings("unused")
    public static void main(String args[]) {

        // HashSet
        Set<ClassA> hashSetA = new HashSet<ClassA>() {
            {
                add(new ClassA("name", 1, "desc"));
                add(new ClassA("name", 2, "desc"));
                add(new ClassA("name", 3, "desc"));
            }
        };

        Set<ClassA> hashSetB = new HashSet<ClassA>() {
            {
                add(new ClassA("name", 1, "desc"));
                add(new ClassA("name", 2, "desc"));
                add(new ClassA("name", 3, "desc"));
            }
        };

        TreeSet<ClassA> treeSetA = new TreeSet<ClassA>(new CompareID()) {
            {
                addAll(hashSetA);
            }
        };

        TreeSet<ClassA> treeSetB = new TreeSet<ClassA>(new CompareID()) {
            {
                addAll(hashSetB);
            }
        };

        if (treeSetA.equals(treeSetB))
            System.out.println("Equal set of tree");
        else
            System.out.println("Unequal set of tree");   // this is result.
    }}

A 类给出如下:

class ClassA {
String name;
int id;
String desc;

public ClassA(String name, int id, String desc) {
    this.name = name;
    this.id = id;
    this.desc = desc;
}

    int getId() {
        return id;
    }
}

class CompareID implements Comparator<ClassA> {
    @Override
    public int compare(ClassA o1, ClassA o2) {
        if (o1.getId() > o2.getId())
            return 1;
        else
            return -1;
    }
}

编辑: 我试过if (treeSetA.containsAll(treeSetB) && treeSetB.containsAll(treeSetA)此条件也。但结果相同,"Unequal set of tree"

最佳答案

您的 compare 方法始终返回不等式。

来自文档:

[...]

a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.

[..]

public int compare(ClassA o1, ClassA o2) {
    if (o1.getId() > o2.getId())
        return 1;
    else if(o2.getId() > o1.getId())
        return -1;
    // 0  indicates equality.
    else return 0;
}

在输出中包含此结果

Equal set of tree

关于java - 比较树集是否相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39370180/

相关文章:

java - 初始化 StandardFileSystemManager 的最佳实践是什么

c# - 集合行为中的奇怪 C# 结构

java - 带有 GNU trove 的整数排序集

java - 我们是否应该在 JavaFX 自定义控件中使用 FXML?

java - 在接口(interface)方法中返回子类

Java集合排序和自定义排序-速度

java - 对Hashmap值进行排序compareTo方法

Java TreeSet<int[]> : duplicate elements?

Java:为什么我的 HashSet 和 TreeSet 包含重复项?

java - 在 Java 中生成音调并改变它的音色?