2013-04-09 21 views
1

Let's说我有一个插入一个编号的方法为二叉树在java中将真实数字投射到Comparable?

public BinaryNode insert(Comparable x, BinaryNode t) { 
    //Logic here 
} 

BinaryTree t = new BinaryTree(); 

我怎么会投一个号码,例如4,以匹配该方法正确paremeters?防爆。

t.insert(4, t) // I know this wont work, but I wanted to to something like this 

回答

4

它应该工作正常 - 它会被装箱成一个整数。示例代码:

public class Test { 

    static void foo(Comparable<?> c) { 
     System.out.println(c.getClass()); 
    } 

    public static void main(String args[]) throws Exception { 
     foo(10); 
    } 
} 

这工作,即使你使用原始类型Comparable,但我建议针对。

诚然,我强烈怀疑你会更好,让您的BinaryNode(大概BinaryTree)类通用,在这一点你必须:

// You shouldn't need to pass in the node - the tree should find it... 
BinaryTree<Integer> tree = new BinaryTree<Integer>(); 
tree.insert(10); 
0

如果你通过新的整数它应该工作( 4)而不是4假设你使用5以前的Java版本(因为你说它不工作)。