1

I get the following error when trying to create an array of Nodes:

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [LSkipList$Node;

This is my code:

    public class Node {
      Key key;
      Value val;
      Node[] next;

      //constructor
      public Node(Key k, Value v) {
        key = k;
        val = v;
        next = (Node[])new Object[MAX_LEVEL];

      }
    }
1
  • 2
    Why are you making a new array of objects and casting it to an array of nodes instead of just making an array of nodes? Commented Dec 8, 2018 at 1:05

1 Answer 1

1

This:

new Object[MAX_LEVEL]

means "a new array of type Object[] and size MAX_LEVEL where every element is null".


This:

(Node[])new Object[MAX_LEVEL]

means the same, plus "but check if it has type Node[]; if not, raise ClassCastException". But that's redundant, because you just created the array with type Object[], so you know it doesn't have type Node[]. So it will always raise ClassCastException.


Instead, you need to write this:

new Node[MAX_LEVEL]

which means "a new array of type Node[] and size MAX_LEVEL where every element is null".

Sign up to request clarification or add additional context in comments.

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.