Search code examples
javacastingnumbersintegercomparable

Casting a real number to Comparable in java?


Let´s say I have a method that inserts a number into a Binary Tree

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

BinaryTree t = new BinaryTree();

How would I cast a number , for example 4 to match the right paremeters on this methods? Ex.

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

Solution

  • It should work fine - it'll be boxed into an integer. Sample code:

    public class Test {
    
        static void foo(Comparable<?> c) {
            System.out.println(c.getClass());
        }
    
        public static void main(String args[]) throws Exception {
            foo(10);
        }
    }
    

    This works even if you use the raw type Comparable, although I'd recommend against that.

    Admittedly I strongly suspect that you'd be better off making your BinaryNode (and presumably BinaryTree) class generic, at which point you'd have:

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