Reputation: 137
Can someone explain why I am getting this error: The method compareTo(AVLNode) is undefined for the type AVLNode
Here is a shortened version of my Tree class:
public class AVLTree< E extends Comparable<E> >
{
private AVLNode<E> root ;
public AVLTree()
{
this.root = null;
}
public void insert ( AVLNode<E> item )
{
if( item.getLeft().compareTo(item.getItem() ) < 0) //ERROR IS HERE
{
}
}
}
Below is my a short version of my Node class
class AVLNode <E extends Comparable<E> >
{
private AVLNode<E> item;
private AVLNode<E> left;
public AVLNode ( AVLNode<E> item)
{
this.item = item;
this.left = null;
}
public AVLNode( AVLNode<E> item, AVLNode<E> lft )
{
this.item = item;
this.left = lft;
}
public AVLNode<E> getItem()
{
return this.item;
}
public AVLNode<E> getLeft()
{
return this.left;
}
}
Upvotes: 1
Views: 153
Reputation: 8386
Your AVLNode
class should obviously look like this:
public class AVLNode<E extends Comparable<E>> {
private E item;
//...
public int compareTo(final E obj) {
return this.item.compareTo(obj);
}
Difference:
item
should be of type E
not AVLNode<E>
because you want to store an E and not a AVLNode
.To state, that your AVLNode
s are comparable, they could implement Comparable<T>
themself by just delegating to E#compareTo()
method:
public class AVLNode<E extends Comparable<E>> implements Comparable<AVLNode<E>> {
private E item;
//...
@Override
public int compareTo(final AVLNode<E> other) {
return this.item.compareTo(other.item);
}
}
Upvotes: 1
Reputation: 6532
That's because AVLNode
doesn't have a method called compareTo()
if you implement one then the issue should be solved.
You should also decide whether your want to compare E
vs E
or AVLNode
vs AVLNode
Upvotes: 0
Reputation: 59104
getLeft()
returns an AVLNode
. You try and call getLeft().compareTo(...)
. This requires that AVLNode
provides a matching method.
From this:
class AVLNode <E extends Comparable<E> >
{
private AVLNode<E> item;
...
It looks like your nodes can only hold other nodes. Presumably your items should actually be of the comparable type E
. Then you can retrieve the item and call compareTo()
on that.
Upvotes: 0
Reputation: 5443
Your Comparable
base class assumes you're comparing to E
s when you want to compare to AVLNode<E>
s
So change it to inherit Comparable<AVLNode<E>>
and see what happens.
Upvotes: 3