I have a line of code like this:
List<string>[] apples = new List<string>()[2];
Its purpose is simply to create an array of List objects. When I try to compile my code, the above line generates this error:
Cannot implicitly convert type 'string' to 'System.Collections.Generic.List[]
I haven't been able to find much on the subject of creating an array of List objects (actually only this thread), maybe because no search engines will search for brackets.
Is the only way to create a collection of Lists to put them in another list, like below?
List<List<string>> apples = new List<List<string>>(); //I've tried this and it works as expected
Thanks for any suggestions, I'm really just curious as to why the first line of code (the List[] example) doesn't work.
Answer: Yes. Java can have an array of objects just like how it can have an array of primitive types.
Lists can be converted to arrays using the built-in functions in the Python numpy library. numpy provides us with two functions to use when converting a list into an array: numpy. array()
You can do this. The syntax would be:
List<string>[] apples = new List<string>[2];
Note that this only allocates an array of references - you'll need to actually construct the individual list elements before you use them:
List<string>[] apples = new List<string>[2];
apples[0] = new List<string>();
apples[1] = new List<string>();
Alternatively, you can use the collection initialization syntax (works well for small numbers of fixed elements), ie:
List<string>[] apples = new[] { new List<string>(), new List<string>() };
Try this:
List<string>[] apples = new List<string>[2];
You do the initialization of each list afterwards:
apples[0] = new List<string>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With