Java 树类的可比性实现
我的任务是处理哈夫曼编码,我使用树的优先级队列来创建它。我正在尝试为我的树类实现comparable,然后使用CompareTo方法,以便可以按频率在优先级队列中对树进行排序。我在尝试这样做时收到一些错误消息,我不知道为什么Java 树类的可比性实现,java,tree,huffman-code,Java,Tree,Huffman Code,我的任务是处理哈夫曼编码,我使用树的优先级队列来创建它。我正在尝试为我的树类实现comparable,然后使用CompareTo方法,以便可以按频率在优先级队列中对树进行排序。我在尝试这样做时收到一些错误消息,我不知道为什么 n00832607.java:249: error: Tree is not abstract and does not override abstract method compareTo(Object) in Comparable class Tree implem
n00832607.java:249: error: Tree is not abstract and does not override abstract method
compareTo(Object) in Comparable
class Tree implements Comparable
^
n00832607.java:423: error: method does not override or implement a method from a supertype
@Override
^
这是给我带来麻烦的代码
//Begin tree class
class Tree implements Comparable
{
private Node root; // first node of tree
// -------------------------------------------------------------
public Tree(char data, int frequency) // constructor
{
root = new Node();
root.iData = frequency;
root.dData = data;
}
public Tree(Tree leftChild, Tree rightChild)
{
root = new Node();
root.leftChild = leftChild.root;
root.rightChild = rightChild.root;
root.iData = leftChild.root.iData + rightChild.root.iData;
}
protected Tree(Node root)
{
this.root = root;
}
//end constructors
//Misc tree methods inbetween the constructors and compareTo, I can post them if that would help
@Override
public int compareTo(Tree arg0)
{
Integer freq1 = new Integer(this.root.iData);
Integer freq2 = new Integer(arg0.root.iData);
return freq1.compareTo(freq2);
}
} // end class Tree
////////////////////////////////////////////////////////////////
如果有帮助的话,这里还有我的节点类
//Begin node class
////////////////////////////////////////////////////////////////
class Node
{
public int iData; // data item (frequency/key)
public char dData; // data item (character)
public Node leftChild; // this node's left child
public Node rightChild; // this node's right child
public void displayNode() // display ourself
{
System.out.print('{');
System.out.print(iData);
System.out.print(", ");
System.out.print(dData);
System.out.print("} ");
}
} // end class Node
////////////////////////////////////////////////////////////////
您使用的是原始
Comparable
类型,而不是泛型Comparable
类型。因此,要按原样编译,compareTo()方法应该将对象作为参数,而不是树。当然,解决这个问题的正确方法是让类实现可比性
另外,请注意,不必在每次比较时创建两个新的整数实例,您只需使用(因为Java 7):
非常感谢,这解决了我的问题。我还有一个关于HashMaps的问题,我应该编辑我的问题还是创建一个新的问题?
return Integer.compare(this.root.iData, arg0.root.iData);