Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing a List with arrays

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>

like image 216
dukevin Avatar asked Dec 03 '15 22:12

dukevin


People also ask

How do you initialize an ArrayList in Python?

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.

Can you initialize an ArrayList with an array?

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" ) );

Can you initialize an ArrayList with values?

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.


1 Answers

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" }
    };
like image 133
AJ X. Avatar answered Oct 19 '22 04:10

AJ X.