Not sure what is going on here. Seems like an auto-boxing problem but I've been stuck on this for awhile and thought it might benefit me to stop stressing out and get some more experienced hands on this. The assignment is essentially implementing a BST and extending it to an implementation of an AVL and then running performance tests. To simplify things we can stick with using Integer as the generic.
The problem I am having is when comparing two Nodes. Autoboxing is not taking place and the intValue() method is not recognized.
public class BinaryNode<Integer> implements Comparable<Integer>
{
Integer data;
BinaryNode<Integer> leftChild;
BinaryNode<Integer> rightChild;
int height;
BinaryNode(Integer data)
{
this(data, null, null);
}
BinaryNode(Integer data, BinaryNode<Integer> lt, BinaryNode<Integer> rt)
{
this.data = data;
this.leftChild = lt;
this.rightChild = rt;
}
public Integer getData()
{
return this.data;
}
public BinaryNode<Integer> getLeft()
{
return leftChild;
}
public void setLeft(BinaryNode newNode)
{
this.leftChild = newNode;
}
public BinaryNode<Integer> getRight()
{
return rightChild;
}
public void setRight(BinaryNode newNode)
{
this.rightChild = newNode;
}
@Override
public int compareTo(BinaryNode<Integer> otherNode)
{
return this.getData() - otherNode.getData();
}
}
Edit: Thanks for the quick feedback. It was just the sort of interaction I needed to look at this differently and understand the quirky behavior I was encountering. Unfortunately I am bound to make this BinaryNode a generic class but the trick was to swap out all of the with or as the book's conventions prefer to use .
The best solution was to change the BinaryNode<Integer> to BinaryNode<AnyType> and remove the compareTo from this class. Now that I am no longer overshadowing java.lang.Integer I can reliably use the Integer.compareTo method as I originally intended.
For the curious, here is the TreePrinter class that I have to interact with that uses the parameterized BinaryNode class. http://www.cs.sjsu.edu/~mak/CS146/assignments/3/TreePrinter.java
In class BinaryNode<Integer>
, Integer is a generic type parameter, not the Integer class.
change
public class BinaryNode<Integer> implements Comparable<Integer>
to
public class BinaryNode implements Comparable<Integer>
And change any appearance of BinaryNode<Integer>
to BinaryNode
.
If you wanted the BinaryNode class to takes a generic data type, you wouldn't write code specific to Integer data type (for example, return this.getData() - otherNode.getData()
will never compile if getData()
returns some generic type parameter T).