Search code examples
javatreeextendscomparable

extending a class AND comparable in a generic java data structure


For homework I was assigned to make an AVL Tree data structure. I am trying to make my "add" method to add a piece of generic data to the tree. My problem is that in the assignment we must extend a class that was given to us called "BinaryTree". Within my add method I need to use the compareTo method, which I believe means that I also have to Extend Comparable. I have looked online and apparently you cannot extend two classes so this becomes a problem. I decided to try to write my own compareTo method in my AVL tree class but it says the < and > cannot be applied to my generic type. Any hints or quick workarounds? or am I just being dumb?

Thanks - Steve


Solution

  • You can use Generics to specify the type and require that it implements Comparable. That way you have access to both the type and compareTo() within the AVL Tree.

    public class AVL<T extends Comparable<T>> extends BinaryTree {
    
        public void add(T object) {
                ...
            object.compareTo(some other object)
                ...
        }
    }
    

    Then you would create it as AVL<MyObject> avl = new AVL<MyObject>()