Reputation: 765
I am trying to define a generic class which can work with any data type with Comparable
interface defined.
The error message is compareTo(Key) in java.lang.Comparable<Key> cannot be applied to (java.lang.Comparable) on line 22
TreeNode
class declaration, but I cannot figure out what it is.
Warnings [unchecked] unchecked call to TreeNode(Key) as a member of the raw type findLargestKElementsInTree.TreeNode on line 16
class findLargestKElementsInTree<Key extends Comparable<Key>>{
TreeNode root;
int count=1;
public void insert(Key k)
{
this.insert(k,root,root);
}
private void insert(Key k, TreeNode node,TreeNode parent)
{
if(this.root==null)
root=new TreeNode(k);
if(node==null)
{
node=new TreeNode(k);
if(parent != null)
{
if(k.compareTo(parent.data)<0)
parent.left=node;
else
parent.right=node;
}
}
else
{
if(node.data.compareTo(k)>0)
insert(k,node.left,node);
else if(node.data.compareTo(k)<0)
insert(k,node.right,node);
else
return;
}
}
public void printK(int k)
{
postOrderK(root,k);
}
/*
* 42
* 40
* 20 25
* 10
* 5
*
*
*
* */
public void postOrderK(TreeNode n,int k)
{
if(n==null)
return;
if(n.right!=null)
postOrderK(n.right,k);
if(count <= k)
{
System.out.println(count+" largest number "+n.data);
count++;
}
postOrderK(n.left,k);
}
public class TreeNode<Key extends Comparable<Key>>{
Key data;
TreeNode left;
TreeNode right;
TreeNode(Key d)
{
this.data=d;
this.left=null;
this.right=null;
}
}
public static void main(String[] args)
{
findLargestKElementsInTree<Integer> tree=new findLargestKElementsInTree<Integer>();
tree.insert(20);
tree.insert(40);
tree.insert(10);
tree.insert(5);
tree.insert(42);
tree.insert(25);
tree.printK(7);
}
}
I have looked at other questions on stack overflow which seem to be helping out with similar problem, but the solution suggested is to have a generic class, I think I already have that.
Thanks in advance!
Upvotes: 0
Views: 2574
Reputation: 200168
Look at your method's signature:
private void insert(Key k, TreeNode node, TreeNode parent) {
Your node
and parent
parameters have the raw TreeNode
type, but TreeNode
is a generic class. Fix it by parameterizing as appropriate:
private void insert(Key k, TreeNode<Key> node, TreeNode<Key> parent) {
Same for the root
, left
, and right
instance variables.
Upvotes: 4
Reputation: 393836
I think what you are missing is declaring the root
instance to use the generic type TreeNode<Key>
instead of the raw type TreeNode
:
class findLargestKElementsInTree<Key extends Comparable<Key>>{
TreeNode<Key> root;
...
You should probably replace every place that has the raw type TreeNode
with TreeNode<Key>
.
Upvotes: 1