Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java generics - type mismatch from T to T

Tags:

java

generics

I was trying to implement a basic Binary Search Tree (irrelevant to the question). This is what I have:

public class BSTNode<T> {
    public T data;
    public BSTNode<T> left;
    public BSTNode<T> right;
}


public class BinarySearchTree<T> {
    private BSTNode<T> root;

    public <T> BSTNode<T> insert(T item){
        BSTNode<T> newNode = new BSTNode<T>();
        newNode.data = item;

        if(root == null){
            root = newNode;
        }

        return newNode;
    }
}

The insert method is not complete. But, I am getting the following compilation error on 'root = newNode;' line in the if block:

Type mismatch: cannot convert from BSTNode<T> to BSTNode<T>

I am unable to wrap my head around this. They are the same generic type. Why would the compiler complain?

I am using JDK 8 with Eclipse Mars.

like image 766
sreenisatish Avatar asked Jan 07 '23 00:01

sreenisatish


2 Answers

Those are two type parameters with the same name. One from here:

public class BinarySearchTree<T>

and one from here:

public <T> BSTNode<T> insert
       ^^^

Get rid of the one the arrows are pointing at. You've made the method take its own T parameter distinct from the class's T.

like image 145
user2357112 supports Monica Avatar answered Jan 18 '23 05:01

user2357112 supports Monica


public <K> BSTNode<K> insert(K item){

}

and use K in your method instead of T

Because you need another identifier for param in parametrized method, T is already used for class.

like image 36
ikos23 Avatar answered Jan 18 '23 05:01

ikos23