gpt4 book ai didi

java - 等于整数

转载 作者:行者123 更新时间:2023-12-02 06:00:22 25 4
gpt4 key购买 nike

我正在创建二叉树。我不能等于整数,但在我的类(class)中它是有效的。这是部分代码:

In tree...

public void add(BTree<T> tree, T newValue){

if(newValue.equals(getValue())){
System.out.println("equals, incrementing count...");
tree.count.incrementAndGet();
}else if(newValue.compareTo(tree.getValue()) > 0){
addRight(tree, newValue);
//It will back here with another node
}else{
addLeft(tree, newValue);
//It will back here with another node
}
}

In main...

BTree<Integer> tree = new BTree<>(0);
tree.add(tree, 1);
tree.add(tree, 1);
tree.add(tree, 1);
tree.add(tree, -1);

System.out.println(tree.getLeftChild().getValue() + "(" + tree.getLeftChild().getCount() + ")" + " " + tree.getRightChild().getValue() + "(" + tree.getRightChild().getCount() + ")");

In console...

-1(1) 1(1)

如何等于两个值?

最佳答案

您对 equals 的定义似乎与 compareTo 不一致。这可不是什么好事。

尽管您可以通过专门使用 compareTo 来解决这个问题,如下所示:

int cmpResult = newValue.compareTo(tree.getValue();
if (cmpResult == 0){
System.out.println("equals, incrementing count...");
tree.count.incrementAndGet();
}else if(cmpResult > 0){
addRight(tree, newValue);
}else{
addLeft(tree, newValue);
}

Java documentation for the Comparable interface强烈建议您解决该问题:

It is strongly recommended (though not required) that natural orderings be consistent with equals. This is so because sorted sets (and sorted maps) without explicit comparators behave "strangely" when they are used with elements (or keys) whose natural ordering is inconsistent with equals. In particular, such a sorted set (or sorted map) violates the general contract for set (or map), which is defined in terms of the equals method.

关于java - 等于整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22720605/

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