I want to create a simple Binary Search Tree which uses generics to specify the data type. However, when I want to create a new tree of Integers, I get the following error:
type argument java.lang.Integer is not within bounds of type-variable T
I tried other data types which are clearly extending Comparable, so why is this not working?
Here is my code:
Interface:
public interface Comparable<T>
{
int compareTo( T t );
}
BinarySearchTree:
public class BinarySearchTree<T extends Comparable<T>>
{
private T content;
private BinarySearchTree<T> leftChild, rightChild;
public BinarySearchTree()
{
content = null;
leftChild = null;
rightChild = null;
}
public T getContent()
{
if(!isEmpty())
{
return content;
}
else
{
throw new RuntimeException();
}
}
public boolean isEmpty()
{
return content == null;
}
public boolean isLeaf()
{
return !isEmpty() && leftChild.isEmpty() && rightChild.isEmpty();
}
public void add(T t)
{
if(isEmpty())
{
content = t;
leftChild = new BinarySearchTree<T>();
rightChild = new BinarySearchTree<T>();
}
else
{
if(content.compareTo(t) > 0)
{
leftChild.add(t);
}
if(content.compareTo(t) < 0)
{
rightChild.add(t);
}
}
}
public int size()
{
if(isEmpty())
{
return 0;
}
else
{
return 1 + leftChild.size() + rightChild.size();
}
}
public boolean contains(T t)
{
if(isEmpty())
{
return false;
}
else
{
if(content.compareTo(t) > 0)
leftChild.contains(t);
else if(content.compareTo(t) < 0)
rightChild.contains(t);
return true;
}
}
public void show()
{
if(!isEmpty())
{
leftChild.show();
System.out.println(content);
rightChild.show();
}
}
}
Main:
public class main
{
public static void main(String[] args)
{
test();
}
public static void test()
{
BinarySearchTree<Integer> tree = new BinarySearchTree<>();
tree.add("5");
tree.add("10");
tree.add("3");
tree.add("1");
tree.show();
}
}
The error comes with this line: BinarySearchTree<Integer> tree = new BinarySearchTree<>();
BinarySearchTree<Integer>?Comparable, then this is indeed exacrly the problem -Integeris-ajava.lang.Comparable<Integer>, but you seem to expect it to be of your ownComparabletype, and that is not true. It would've been if Java supported duck typing, but it doesn't.