2

I'm trying to make a linked-list representation of Deque , each node of the linked list is defined by an instance of the inner class Node , but I'm getting this :

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [LRandomizedQueue$Node;

I dony know how to work this out. This is what i had:

private class Node {
        Item item;
        Node next;
        Node prev;
    }

    @SuppressWarnings("unchecked")
    private Node[] nd = (Node[]) new Object[100];

Can someone please tell me what i'm doing wrong , and help me figure this out ? Thanks a lot for your time.

Edit: It seems i had things confused with creating a generic array vs an array of an inner class. Thanks a lot for the replies.

2
  • You're creating an Object[] and trying to cast it to a Node[]. Would you expect Node node = (Node) new Object() to work? Commented Sep 11, 2013 at 8:07
  • Always quite a good idea not to have @SuppressWarnings("unchecked") Commented Sep 11, 2013 at 8:07

5 Answers 5

2

You're creating an array of Objects and then trying to cast them to an array of Nodes; you need to create an array of Nodes

try

private Node[] nd = new Node[100];
Sign up to request clarification or add additional context in comments.

Comments

1
private Node[] nd = (Node[]) new Object[100];

It Should throws ClassCastException. It is not possible to cast array object to Node object.

Create like -

Node[] nd = new Node[100];

1 Comment

It's worth noting it's possible the other way around, while it (arguably) shouldn't
1
private Node[] nd = (Node[]) new Object[100];

Why would you do this?

You are clearly casting wrong objects to wrong reference types.

The object is of type Object[] and you are casting it to Node[], which will never work.

Do this instead.

Node[] nd = new Node[size];

Comments

0

you are creating an object array and try to cast it to Node array. this kind of casting is not allowed because object is not a Node

you can do

Node[] nd = new Node[100];

if you need an array of Node or

Object[] nd = new Object[100];

if you need just an array of objects

for future, you should know that usually when you get ClassCastException that means you have tried to cast a class to other class when the case is invalid, and should try to understand the hierarchy of the objects

Comments

0

You essentially need : private Node[] nd = new Node[100];

Because Arrays are themselves objects, since new Object[100] will return an object of array class you can't cast it into some other class object which here is Node.

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.