Casting Issue for Generic Array of Node Objects

Tags: , , ,

I am having problem with java generic array creation where I needed to make an array of type Node.

So, I did this for declaration:

private Node<E> [] nodes; and later for initialization, nodes = (Node<E>[]) new Node [values.length];

When I try to do something like set the Node object’s attribute value nodes[i].setValue(values[i]); , I get NullPointerException, meaning that there is something wrong with my node array setup.

What did I do wrong? Is it the result of incorrect casting, or something else in my code?


In Java, when initializing an array, objects in the array will all initially be set to null by default. So when you call nodes = (Node<E>[]) new Node [values.length], although you are creating an array of nodes, they are all initially set to null. In order to fix this, you will need to manually construct each node in your array with a for loop, i.e,

for (int i = 0; i < values.length; i++) {
    nodes[i] = new Node();

Source: stackoverflow