incompatible type wile returning generic method of statictype

Viewed 51

I tried to implement a BST class was like

class BST<T> {
   private Node<T> root;
   private static class Node<T> {
     T element;
     Node<T> left;
     Node<T> right; 
   }  
}

I want to get the successor node in a method which takes a Node as a parameter and returns a successor node

private <T> Node<T> get(Node<T> current node){  
    Node<T> successor = root; 
}

here I'm getting incompatible types . if I remove the method bound

private Node<T> get(Node<T> current node) {
    Node<T> successor = root;
}

now it is compiling fine. What is the reason?

2 Answers

reason is T has already been defined at class level BST<T>. which means that you have to use BST<String>.method(); If you remove <T> from BST, the type will then have to be specified at the method level and you will need to add <T> at your method declaration. And calling the method will be BST.method<String>();

Your current code(which doesn't compile) reads as :

static class BST<T> {
    private Node<T> root;

    private static class Node<T> {
        T element;
        Node<T> left;
        Node<T> right;
    }

    //       
    private <S> Node<T> get(Node<T> currentNode) {
        Node<S> successor = root;
        return null;
    }
}

now you could easily relate by Node<S> couldn't be compatible with Node<T>, right?

Because of the presence of the method bound, the compiler treats both the method bound and the successor bound to be the same in this case. But the bound represented in the class BST<T> is not the same as bound represented by <T> Node<T> get method further still and that's where the incompatibility arises from.

If you wish to use the same bound, you could simply change the above code to get rid of your method bound, which is where you don't see any compile errors. Since then the bound of successor is inferred as the same as the bound of the class BST.

Related