【问题标题】:Implementing comparable for Tree class为 Tree 类实现可比较
【发布时间】:2014-03-09 16:22:00
【问题描述】:

我的作业涉及霍夫曼编码,我使用树的优先级队列来创建它。我正在尝试为我的 Tree 类实现可比较,然后有一个 compare To 方法,以便可以按频率在优先级队列中对树进行排序。尝试执行此操作时收到一些错误消息,我不知道为什么。

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
////////////////////////////////////////////////////////////////

如果有帮助的话,这也是我的 Node 类

//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
////////////////////////////////////////////////////////////////

【问题讨论】:

    标签: java tree huffman-code


    【解决方案1】:

    您正在使用原始的 Comparable 类型,而不是使用通用的 Comparable<Tree> 类型。因此,要按原样编译,您的 compareTo() 方法应该将 Object 作为参数,而不是 Tree。但当然,修复它的正确方法是让你的类实现Comparable<Tree>

    另外,请注意,您可以简单地使用(从 Java 7 开始),而不是在每次比较时创建两个新的 Integer 实例:

    return Integer.compare(this.root.iData, arg0.root.iData);
    

    【讨论】:

    • 非常感谢,解决了我的问题。我还有一个涉及 HashMaps 的问题,我应该编辑我的问题还是创建一个新问题?
    猜你喜欢
    • 2021-02-01
    • 2011-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多