Registered User
Registered User

Reputation: 2299

What are generic arrays in Java?

I have a code, whose MCVE is like this

import java.util.LinkedList;

public class Test
{
    LinkedList<Node>[] arr;

    Test(){
        arr = new LinkedList<Node>[4];
    }

    public static void main(){
    }
}

class Node{   
}

where I get this error

error: generic array creation
        arr = new LinkedList<Node>[4];
              ^

I looked for the error and found these two posts How to create a generic array in Java? and Error: Generic Array Creation

But I don't understand what a generic array is. I guess(from what I get from the two posts) it means array that does not know what type it's going to store, but in my case the array is specified to be of LinkedList<Node> type.

Can someone explain the concept?

Upvotes: 0

Views: 94

Answers (1)

lexicore
lexicore

Reputation: 43671

Please check the following answer:

https://stackoverflow.com/a/18581313/303810

Since it is a bit large, I'll sum up the relevant part here.

LinkedList<Node>[] is a generic array as it has generic type of the component. The problem with this consruct is that you could do the following:

LinkedList<Node>[] listsOfNodes = new LinkedList<Node>[1];
Object[] items = listsOfNodes;
items[0] = new LinkedList<String>();

So at this point listsOfNodes[0] which should have had the type LinkedList<Node> would be an instance of LinkedList<String>.

Upvotes: 1

Related Questions