0

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?

Community
  • 1
  • 1
Registered User
  • 2,239
  • 3
  • 32
  • 58
  • Read [this answer](http://stackoverflow.com/a/18581313/303810), especially **What about creating an array of type List[]?** part – lexicore Jan 27 '17 at 12:02
  • @JoeClay What's wrong with `LinkedList[]`? How do you know OP doesn't intend to have an array of lists? – lexicore Jan 27 '17 at 12:04
  • @JoeClay I don't get what you mean. arr is an array of linkedlists of nodes. So `new LinkedList[4]` seems correct to me. Wont removing the brackets create only a single linkedlist of nodes? – Registered User Jan 27 '17 at 12:08
  • Ah, I couldn't tell from your question whether you were getting the syntax mixed up or whether you actually intended to have an array of lists. My bad! – Joe Clay Jan 27 '17 at 12:25

1 Answers1

1

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>.

Community
  • 1
  • 1
lexicore
  • 42,748
  • 17
  • 132
  • 221