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.
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
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments