2014-03-28 60 views
0

我正在创建二叉树。我不能等于整数,但在我的课程中,它的工作原理。以下是部分代码:等于整数

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) 

我该如何等于两个VALUES?

+0

_我如何等于两个VALUES?_ **使用正确实施的'equals()'方法** –

+0

你能告诉我怎么做吗? – rberla

+0

* if(newValue.equals(getValue()))*什么是getValue? – bengoesboom

回答

2

看来您的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强烈建议你来解决这个问题:

强烈推荐(虽然不要求)自然排序与equals一致。这是因为,如果排序集(和排序映射)没有显式比较器,当它们与自然排序与equals不一致的元素(或键)一起使用时,其行为会“奇怪”。特别是,这样一个有序的集合(或有序的映射)违反了集合(或映射)的一般合约,这是根据equals方法定义的。

+0

谢谢!错误在“树”中。比没有写) – rberla