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)
new Object[10]isObject[]. It's notSinglyLinkedListNode<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?