7

Per the docs on Lists, I can use array notation to create a list of pre-allocated length:

List<String> colors = new String[1];

However, replacing the primitive String type with a list doesn't work, but produces unexpected token: '[':

List<List<String>> colorLists = new List<String>[1]; // DOES NOT COMPILE

Further exploration shows that you also can't use bracket notation without a fixed size:

List<List<String>> colorLists = new List<String>[]; // ALSO DOES NOT COMPILE

Specifically, the docs state, "... you can declare a one-dimensional list of primitives or objects by following the data type name with the [] characters." So are collections not considered "objects", is this a bug, or am I overlooking something?

0

1 Answer 1

11

The syntax changes slightly when you use the parameterized syntax:

List<List<String>> colorLists = new List<List<String>>(1);

If you want the list to be empty, do not provide a parameter (or use 0):

List<List<String>> colorLists = new List<List<String>>(0);

[] is syntactic sugar, but it doesn't always work. For example, you can't write two-dimensional lists like this:

String[][] colorLists; // DOES NOT COMPILE
List<String>[] colorLists; // ALSO DOES NOT COMPILE

But you can make the inner list using []:

List<String[]> colorLists = new List<String[]>(0);

It's really quite an annoyance, especially coming from a C/C++/Java background like myself, but it's just a matter of syntax.

The docs kind of hint at this by saying:

Using Array Notation for One-Dimensional Lists

That is, you can use the shorthand notation for one-dimension lists, but not for multi-dimensional lists of any combination.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .