0

I'm trying to make my own generic linkedlist data type but am having trouble with the constructor and am getting a class cast exception. Anyone know how to fix this and WHY this is happening?

Here is my relevant code:

public class SinglyLinkedList<E> {

   private LinkedListNode<E>[] linkedListNodeList;

   public SinglyLinkedList()
   {
       linkedListNodeList = (SinglyLinkedListNode<E>[]) new Object[10];
   }

}

The offending line is the implementation line in the constructor.

Here is my SinglyLinkedListNode class:

public class SinglyLinkedListNode<E> extends LinkedListNode<E>{

   private E data;

   public SinglyLinkedListNode(E data)
   {
       this.data = data;
   }
}

And my LinkedListNode class is simply an empty (for now) abstract class that SinglyLinkedListNode extends.

Here is the compiler error I'm receiving:

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [LabstractDataTypes.SinglyLinkedListNode; at abstractDataTypes.SinglyLinkedList.(SinglyLinkedList.java:23)

1
  • 3
    The type of new Object[10] is Object[]. It's not SinglyLinkedListNode<E>[]. Casting an object to a type doesn't change the type of the object. You can't cast a Car to a Bird and hope that the car will transform itself to a bird. You can cast an Animal to a Bird if the animal actually is a bird. That said, why would you need an array of nodes in a linked list? Have you understood what a linked list is? Commented Nov 23, 2013 at 13:39

1 Answer 1

2

An Object[] is not compatible with any other array (e.g. String[]). But this will work:

public class SinglyLinkedList<E> {

   private LinkedListNode<E>[] linkedListNodeList;

   public SinglyLinkedList()
   {
       linkedListNodeList = (SinglyLinkedListNode<E>[]) new SinglyLinkedListNode<?>[10];
   }
}

Note that it is also not possible to use new SinglyLinkedListNode<E>[10], as generic arrays can't be created in general:

E[] myArray = new E[10]; // doesn't work, if E is a generic type parameter
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.