我有两套HashSet
我转换为 TreeSet
对其进行排序以便于比较。转换后HashSet
至TreeSet
。当我使用“等于”函数比较这两个 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/