Java comparing generic types
You can use this simple approach
for data greater than root.getData = 1, for data equals root.getData = 0,for data lesser than root.getData = -1
public class BST<E extends Number & Comparable<? super E>>{
void add(){
...
if(data.compareTo(root.getData()) == 1)
...
}
You cannot overload operators in Java. The <
operator only applies to primitive (or numeric) types, not reference types. Since T
is a type variable that represents a reference type, you cannot use <
on variables of type T
. You have to use
if (item.compareTo(bn.item) < 0)
check the value returned and decide to do what you wish with it.
You don't know what the type T
will be but you know that it will be a type that implements Comparable
and therefore implements the compareTo()
method.