1

この分野の多くの質問を見てきましたが、私の問題を具体的に解決する質問が見つかりません。

基本的に、これは宿題で、要素を保持するノードを含むリンク リストがあります。ノード クラス (LinearNode) と要素クラス (Golfer) はどちらも Comparable を実装し、compareTo メソッドをオーバーライドします。ただし、ランタイムは新しいノードをリストに追加しようとして失敗し (最初のノードは正常に追加されます)、クラス キャスト例外: supersenior.LinearNode を supersenior.Golfer にキャストできません。ノードを取得して、比較対象のノードの要素と比較しようとしている理由がわかりません...明示的にキャストしようとさえしました。次のエラーが発生します。

Exception in thread "main" java.lang.ClassCastException: supersenior.LinearNode cannot      be cast to supersenior.Golfer
at supersenior.Golfer.compareTo(Golfer.java:12)
at supersenior.LinearNode.compareTo(LinearNode.java:80)
at supersenior.LinearNode.compareTo(LinearNode.java:80)
at supersenior.LinkedList.add(LinkedList.java:254)
at supersenior.SuperSenior.main(SuperSenior.java:100)

どんな助けでも大歓迎です。ありがとう!

LinkedList クラス:

package supersenior;
import supersenior.exceptions.*;
import java.util.*;

public class LinkedList<T> implements OrderedListADT<T>, Iterable<T>
{
   protected int count;
   protected LinearNode<T> head, tail;

  /**
  * Creates an empty list.
  */
public LinkedList()
{
  count = 0;
  head = tail = null;
}


public T removeFirst() throws EmptyCollectionException
{
  if (isEmpty())
     throw new EmptyCollectionException ("List");

  LinearNode<T> result = head; 
  head = head.getNext();
  if (head == null)
     tail = null;
  count--;

  return result.getElement();
}


public T removeLast() throws EmptyCollectionException
{
  if (isEmpty())
     throw new EmptyCollectionException ("List");

  LinearNode<T> previous = null;
  LinearNode<T> current = head;

  while (current.getNext() != null)
  {
     previous = current; 
     current = current.getNext();
  }

  LinearNode<T> result = tail; 
  tail = previous;
  if (tail == null)
     head = null;
  else
     tail.setNext(null);
  count--;

  return result.getElement();
}


public T remove (T targetElement) throws EmptyCollectionException, 
     ElementNotFoundException 
{
  if (isEmpty())
     throw new EmptyCollectionException ("List");

  boolean found = false;
  LinearNode<T> previous = null;
  LinearNode<T> current = head;

  while (current != null && !found)
     if (targetElement.equals (current.getElement()))
        found = true;
     else
     {
        previous = current;
        current = current.getNext();
     }

  if (!found)
     throw new ElementNotFoundException ("List");

  if (size() == 1)
     head = tail = null;
  else if (current.equals (head))
     head = current.getNext();
  else if (current.equals (tail))
  {
     tail = previous;
     tail.setNext(null);
  }
  else
     previous.setNext(current.getNext());

  count--;

  return current.getElement();
}


public boolean contains (T targetElement) throws 
     EmptyCollectionException 
{
  if (isEmpty())
     throw new EmptyCollectionException ("List");

  boolean found = false;
  Object result;

  LinearNode<T> current = head;

  while (current != null && !found) 
     if (targetElement.equals (current.getElement()))
        found = true;
     else
        current = current.getNext();

  return found;
}


public boolean isEmpty()
{
  return (count == 0);
}


public int size()
{
  return count;
}


public String toString()
{
  LinearNode<T> current = head;
  String result = "";

  while (current != null)
  {
     result = result + (current.getElement()).toString() + "\n";
     current = current.getNext();
  }

  return result;
}


public Iterator<T> iterator()
{
  return new LinkedIterator<T>(head, count);
}


public T first()
{
  return head.getElement();
}


public T last()
{
  return tail.getElement();
}

@Override
public void add (T element)
{
  LinearNode<T>node = new LinearNode<T>();
  node.setElement(element);

  if(isEmpty())
  {
      head = node;
      if(tail == null)
          tail = head;
      //node.setNext(head);
      //head.setPrevious(node);
      //head.setElement((T) node);
      count++;
  }
  else
  {
      for(LinearNode<T> current = head; current.getNext() != null; current = current.getNext())
          if(node.compareTo((T) current) >= 0)
          {
              current.setPrevious(current);
              current.setNext(current);
          }
          else
          {
              current.setPrevious(node);
          }
      tail.setNext(node);
  }
}
}

LinearNode クラス:

package supersenior;   

public class LinearNode<E> implements Comparable<E>
{
private LinearNode<E> next, previous;
public E element;


public LinearNode()
{
    next = null;
    element = null;
}


public LinearNode (E elem)
{
    next = null;
    element = elem;
}


public LinearNode<E> getNext()
{
    return next;
}


public void setNext (LinearNode<E> node)
{
    next = node;
}


public E getElement()
{
    return element;
}


public void setElement (E elem)
{
    element = elem;
}



@Override
 public int compareTo(E otherElement) {
    return ((Comparable<E>) this.element).compareTo(otherElement);
}

  public LinearNode<E> getPrevious()
{
    return previous;
}


public void setPrevious (LinearNode<E> node)
{
    previous = node;
}

}

要素クラス (ゴルファー):

package supersenior;


public class Golfer implements Comparable<Golfer>{
Golfer imaGolfer;
String name;
int tourneys;
int winnings;
double avg;

public Golfer(String attr[]){
    this.name = attr[0];
    this.tourneys = Integer.parseInt(attr[1]);
    this.winnings = Integer.parseInt(attr[2]);
    this.avg = findAvg(winnings, tourneys);

 }

 private double findAvg(int winnings, int tourneys){
   double a = winnings/tourneys;
   return a;
 }

@Override
 public String toString(){
   return "Name: " + name + " Tourneys: " + tourneys + " Winnings: " + winnings + " Average: " + avg;
}

@Override
public int compareTo(Golfer golfer) {
if(this.avg <= golfer.avg)
    return 1;
if(this.avg == golfer.avg)
    return 0;
else
    return -1;
}
}
4

1 に答える 1

1

問題は、比較対象を混同していることです。LinearNodeオブジェクト ( を保持するE) を実際のと比較しようとしていますELinearNode<E>実装すべきではありませんComparable<E>。どちらかといえば を実装する可能性がComparable<LinearNode<E>>あり、型パラメーターはおそらく である必要がありますE extends Comparable<E>

LinearNode基になる要素の順序に基づいて を順序付けたい場合は、次のようなものを使用する必要があります。

// in LinearNode
public int compareTo(LinearNode<E> otherNode) {
    return this.element.compareTo(otherNode.element);
}

(Java のソートされたコレクションは、要素を実装する必要がないことに注意してください。これは、それらのいずれかにComparableカスタムを提供できるためですが、この割り当ての場合は、おそらくそれを要求しても問題ありません。)ComparatorE extends Comparable<E>

(注 2: Generics を使用している場合、 などのキャスト(Comparable<E>)は危険信号です。Generics システムの目的は、ほとんどの明示的なキャストの必要性を排除することです。)

于 2013-10-10T18:27:38.093 に答える