Cheesegraterr
Cheesegraterr

Reputation: 517

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

Upvotes: 0

Views: 2446

Answers (4)

Reverend Gonzo
Reverend Gonzo

Reputation: 40811

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>()

Upvotes: 3

Paŭlo Ebermann
Paŭlo Ebermann

Reputation: 74750

You normally want to compare the keys in your tree with each other, not one tree with another one, or to a key.

Thus, your key objects should implement Comparable, or better Comparable<K> where K is some supertype of your keys.

This normally means that you would declare your AVLTree class to be generic:

class AVLTree<K extends Comparable<? super K>, V> extends BinaryTree {

   ...

}

I did not really understand the relation to your BinaryTree class, sorry.

Upvotes: 0

Mike Deck
Mike Deck

Reputation: 18397

First of all, java.lang.Comparable is an interface, not a class. Java only allows you to extend one class, but you can implement as many interfaces as you like, so it's perfectly valid to do something like this:

public class MyTreeImpl extends BinaryTree implements Comparable<MyTreeImpl> {

    @Override
    public int compareTo(MyTreeImpl o) {
        // your compare implementation
    }

    // the rest of your class definition
}

To address your issue with generics I think I'd need to see your code and the exact error the compiler was giving you.

Upvotes: 0

CoolBeans
CoolBeans

Reputation: 20800

Java does not support multiple inheritance. However, you do not need to extend Comparable, you need to implement Comparable. Comparable is an interface. You do not extend an interface, you implement it.

Hope this helps.

An example below:-

public final class AVL implements Comparable<SomeObject> extends BinaryTree

Upvotes: 3

Related Questions