1

I've looked at a bunch of the questions in this area and can't find one that solves my problem specifically.

Basically, this is a homework assigment where I have a linked list with nodes, which hold an element. The node class (LinearNode) and the element class (Golfer) both implement Comparable and override the compareTo method. However, the runtime fails trying to add a new node to the list (first node is added fine) with a class cast exception: supersenior.LinearNode cannot be cast to supersenior.Golfer. I don't know why it's trying to take the node and compare it to an element of the node to be compared...i've even tried explicitly casting. The following error is observed:

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)

Any help would be greatly appreciated. Thanks!

LinkedList class:

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 class:

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

}

The element class (Golfer):

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 Answer 1

1

The problem is that you're mixing what's being compared. You're trying to compare the LinearNode object (which holds an E) to an actual E. LinearNode<E> shouldn't implement Comparable<E>; if anything, it might implement Comparable<LinearNode<E>>, and the type parameter should probably be E extends Comparable<E>.

If you want to order LinearNodes based on the ordering of their underlying elements, you should use something like this:

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

(Note that the Java sorted collections don't require elements to implement Comparable, since you can provide a custom Comparator for any of them, but in the case of this assignment it's probably fine to require that E extends Comparable<E>.)

(Note 2: If you're using Generics, any cast, such as your (Comparable<E>), is a red flag; the purpose of the Generics system is to eliminate the need for most explicit casts.)

2
  • Awesome, so to kinda paraphrase in my head, I need to tell the compiler that "Linear nodes can be compared (Comparable<LinearNode<E>>, but my elements inside can be compared too, so please access that functionality which I overrode (LinearNode<E extends Comparable<E>> So the whole line is: public class LinearNode<E extends Comparable<E>> implements Comparable<LinearNode<E>>
    – Java-noob
    Oct 10, 2013 at 19:03
  • But now the issue is that my LinkedList hates everything of type T...do I have to change it to E to match? \supersenior\LinkedList.java:16: error: type argument T is not within bounds of type-variable E protected LinearNode<T> head, tail; where T,E are type-variables: T extends Object declared in class LinkedList E extends Comparable<E> declared in class LinearNode If I change the LinkedList LinearNode type for head and tail to LinearNode<E> instead of LinearNode<T>, it just says it can't find E....
    – Java-noob
    Oct 10, 2013 at 19:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.