Java 相等整数
我正在创建二叉树。我不能等于整数,但在我的课上它是有效的。下面是代码的一部分:Java 相等整数,java,tree,binary-tree,binary-search-tree,Java,Tree,Binary Tree,Binary Search Tree,我正在创建二叉树。我不能等于整数,但在我的课上它是有效的。下面是代码的一部分: In tree... public void add(BTree<T> tree, T newValue){ if(newValue.equals(getValue())){ System.out.println("equals, incrementing count..."); tree.count.incrementAndGet(); }else i
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)
在树中。。。
公共void添加(b树,T newValue){
if(newValue.equals(getValue())){
System.out.println(“等于,递增计数…”);
tree.count.incrementAndGet();
}else if(newValue.compareTo(tree.getValue())>0){
addRight(树,newValue);
//它将与另一个节点一起返回此处
}否则{
addLeft(树,newValue);
//它将与另一个节点一起返回此处
}
}
大体上。。。
BTree树=新的BTree(0);
树。添加(树,1);
树。添加(树,1);
树。添加(树,1);
添加(tree,-1);
System.out.println(tree.getLeftChild().getValue()+”(“+tree.getLeftChild().getCount()+”)+“+tree.getRightChild().getValue()+”(“+tree.getRightChild().getCount()+”);
在控制台中。。。
-1(1) 1(1)
我怎样才能等于两个值?您对
等于的定义似乎与的定义不一致。这不是一件好事
尽管您可以通过专门使用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);
}
强烈建议您解决此问题:
强烈建议(尽管不是必需的)自然顺序与等于一致。这是因为没有显式比较器的排序集(和排序映射)在与自然顺序与等于
不一致的元素(或键)一起使用时表现“奇怪”。特别是,这样的排序集(或排序映射)违反了集合(或映射)的一般契约,该契约是根据equals
方法定义的
我怎么能等于两个值?使用正确实现的equals()
methodif(newValue.equals(getValue()))什么是getValue?谢谢!“树”中有错误。但未写入)