Java generics - type mismatch from T to T

I tried to implement a basic binary search tree (not relevant 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 insertion method is not complete. But I get the following compilation error: "root = newNode;" line in if block:

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

I can't wrap my head around this. They have the same general type. Why is the compiler complaining?

I am using JDK 8 with Eclipse Mars.

+4
source share
2 answers

These are two types of 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 indicated by the arrows. You made the method your own Tparameter, different from the class T.

+7
source
public <K> BSTNode<K> insert(K item){

}

K T

, T .

0

Source: https://habr.com/ru/post/1619644/


All Articles