Search code examples
javagenericstypesstaticcomparable

Java - Static Generic Type using Comparable


Alright, so I've been trying to implement a simple binary search tree that uses a comparable data type by default.

Ignoring all my other methods in the class, this is the general setup I have which I think is pretty standard:

public class BSTNode<E extends Comparable<? super E>>{
     E data;
     BSTNode<E> left;
     BSTNode<E> right;
     //and I'm trying to define a static method(inside of the class) like this:
     public static <E> String displayAscending(BSTNode<E> node){} 
}

But the compiler isn't liking it. Now, I'm kind of new to generic types so I'll explain my understanding of what this does and that might help you in figuring out what's wrong with my thinking.

E extends Comparable So basically an object E that is an extension of Comparable. Comparable having an element that is an ancestor of E, which essentially is an abstract way of saying E can be compared with its other elements using the Comparable interface.

Then in my static method I'm trying to pass the BSTNode recursively. I can't seem to wrap my head around why it's not working. I know If I pass BSTNode<?> it works fine, but that seems dangerous. If someone could explain to me WHY this isn't working I could try and find another solution.


Solution

  • try this

    public static <E extends Comparable<? super E>> String displayAscending(BSTNode<E> node)