java.lang.Comparable中的compareTo(K)< K>不能应用于(java.lang.Comparable) [英] compareTo(K) in java.lang.Comparable<K> cannot be applied to (java.lang.Comparable)
问题描述
我试图定义一个泛型类,它可以使用 Comparable
接口定义的任何数据类型。
错误消息是在java.lang.Comparable< Key>中的 compareTo(Key)不能在第22行应用于(java.lang.Comparable)
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
警告[unchecked]取消选中调用TreeNode(Key)作为第16行的原始类型findLargestKeylementsInTree.TreeNode的成员
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.
谢谢
推荐答案
查看您的方法签名:
Look at your method's signature:
private void insert(Key k, TreeNode node, TreeNode parent) {
您的节点
和父
参数具有原始 TreeNode
类型,但 TreeNode
是一个泛型类。
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) {
left
和 right
实例变量。
这篇关于java.lang.Comparable中的compareTo(K)< K>不能应用于(java.lang.Comparable)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!