简体   繁体   中英

Generic class constructor failing with a class cast exception error at runtime

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)

An Object[] is not compatible with any other array (eg 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM