等于整数



我正在创建二叉树。我不能等于整数,但在我的课上它是有效的。下面是一段代码:

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);
}

Comparable接口的Java文档强烈建议您修复这个问题:

强烈建议(虽然不是必需的)自然排序与equals一致。这是因为没有显式比较器的排序集(和排序映射)在与自然顺序与equals不一致的元素(或键)一起使用时表现得"奇怪"。特别地,这样的排序集(或排序映射)违反了set(或映射)的一般契约,该契约是根据equals方法定义的。

最新更新