有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java类强制转换尝试将compareTo与链接列表中的节点和元素进行比较时出错

我已经研究了这方面的一系列问题,但找不到一个能具体解决我问题的

基本上,这是一个作业分配,我有一个带有节点的链表,其中包含一个元素。节点类(LinearNode)和元素类(Golfer)都实现了Comparable并重写了compareTo方法。但是,运行时无法尝试将新节点添加到列表中(第一个节点可以添加),出现类强制转换异常:supersenior。LinearNode无法强制转换为supersenior。高尔夫球手我不知道为什么它会尝试获取节点并将其与要比较的节点的元素进行比较。。。我甚至试过直接选角。观察到以下错误:

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;
}
}

共 (1) 个答案

  1. # 1 楼答案

    问题是你把被比较的东西混在了一起。您正在尝试将LinearNode对象(它持有E)与实际的E进行比较LinearNode<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,因为您可以为它们中的任何一个提供自定义Comparator,但是在这种赋值的情况下,需要E extends Comparable<E>可能没什么问题。)

    (注2:如果使用泛型,任何类型转换,例如(Comparable<E>),都是一个危险信号;泛型系统的目的是消除对大多数显式类型转换的需要。)