I want to populate a List of string arrays at compile time
something like this:
List<string[]> synonyms = new List<string[]>
{
{ "enabled", "enable", "enabling" },
{ "disabled", "disable", "disabling" },
{ "s0", "s0 state" },
{ "s5", "s5 state" }
};
but I get a compile error:
No overloaded method 'Add' takes 2 arguments
Why is this? It works if they weren't string arrays with List<string>
To initialize an array with the default value, we can use for loop and range() function in python language. Python range() function takes a number as an argument and returns a sequence of number starts from 0 and ends by a specific number, incremented by 1 every time.
To initialize an arraylist in single line statement, get all elements in form of array using Arrays. asList method and pass the array argument to ArrayList constructor. ArrayList<String> names = new ArrayList<String>( Arrays. asList( "alex" , "brian" , "charles" ) );
Java developers use the Arrays. asList() method to initialize an ArrayList. Using asList() allows you to populate an array with a list of default values. This can be more efficient than using multiple add() statements to add a set of default values to an ArrayList.
You aren't creating arrays in your example, try the following:
List<string[]> synonyms = new List<string[]>
{
new[] { "enabled", "enable", "enabling" },
new[] { "disabled", "disable", "disabling" },
new[] { "s0", "s0 state" },
new[] { "s5", "s5 state" }
};
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