質問

My assignment deals with Huffman encoding and I am using a priority queue of trees to create it. I am trying to implement comparable for my Tree class and then have a compare To method so that the Trees can be sorted in the priority queue by frequency. I am getting some error messages when trying to do this and I am not sure why.

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 
^

Here is the code that is giving me trouble.

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

Also here is my Node class if that is of any help

//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
////////////////////////////////////////////////////////////////
役に立ちましたか?

解決

You're using the raw Comparable type, instead of using the generic Comparable<Tree> type. To compile, as is, your compareTo() method should thus take an Object as argument, and not a Tree. But of course, the correct way to fix it is to make your class implement Comparable<Tree>.

Also, note that instead of creating two new Integer instances at each comparison, you could simply use (since Java 7):

return Integer.compare(this.root.iData, arg0.root.iData);
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top