Ljava.lang.Object; cannot be cast to class ClassName

Viewed 1032

I am trying to implement a linked structure using arrays.

public class LinkedArray <E extends Comparable<E>>{
private Node<E>[] array;
private int head;
private int size = 0; 
private int capacity;

@SuppressWarnings("unchecked")
public LinkedArray (){
    capacity = 10;
    array= (Node<E>[]) new Object[capacity];
    head = -1;
    size = 0;
}
}

It has inner node class

private static class Node<T>{
    protected T data = null;
    protected int next = -1;
}

I get the error :

Exception in thread "main" java.lang.ClassCastException: class [Ljava.lang.Object; cannot be cast to class [LinkedArray$Node; ([Ljava.lang.Object; is in module java.base of loader 'bootstrap'; [LinkedArray$Node; is in unnamed module of loader 'app')

For the line

array = (Node<E>[]) new Object[capacity];

What is the reason? How can I create a Node array?

2 Answers

There's no reason to create a Object[] and then cast it (which won't work since Object is not a subclass of Node), just use

array = new Node[capacity];

Object class can't be cast to Node class. You can create No like below: Node[] array = new Node[5];

Related