Pepper Pepper - 2 years ago 78
Java Question

Creating an array of double generic - Java

so I'm trying to create an array of a double generic class, but for some reason it is giving me an error.


Node<K, V>[] table = (Node<K, V>[]) new Object[10];

I'm receiving the following error:

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

So, I was wondering why is it giving me this error and how can I fix it.

Answer Source

An Object[] ins't a Node[] - e.g., you could set an element of an Object[] to be "Hello Word", which you could not do with a Node[]. TL;DR, you should be creating a Node[]:

Node<K, V>[] table = new Node[10];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download