1

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 2

3

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];
Sign up to request clarification or add additional context in comments.

2 Comments

but when I use this how will it know which generic type will be used in Node?
@zibidigonzales Statements like LinkedArray<Integer> la = new LinkedArray<>(); and new LinkedArray<Integer>() // anonymous object will define the generic type to use.
0

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

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

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.