Search code examples
javaarraylistnew-operator

How to Create and Initialize (in Java) a List<String[]> in the same statement? (Editors please NOTE: this *not* the same as just a List<String>)


Is it possible to combine the creation of a List of String[] with the initialization of the first entry in the List?

final List<String[]> rolesCsv = new ArrayList<String[]>();
rolesCsv.add(new String[] {"Role Name","Description"});

In other words, can I combine the above two lines into a single one that both creates and initializes the List?

The List<String[]> does need to be mutable for later adding to the List, yes.

IMPORTANT NOTE for EDITORS: Creating and initializing this definition is far different than solutions for simply creating and initializing List<String>- BEFORE you automatically link this question to the common answers for the latter, please stop! The problem is different and requires a different solution.


Solution

  • The correct answer was given in the comments (above) by @user16320675 , and this works well. It handles both the creation of the outer List and the internal array of strings. Other answers pointing to a simple Array asList are for simple strings, which is not the question that was asked.

    to create a mutable list

    final List<String[]> rolesCsv =
         new ArrayList<String[]>Collections.singletonList(new String[]{"Role Name","Description"}));
    

    Otherwise (despite the array, its element, will not be immutable)

    final List<String[]> rolesCsv =
          Collections.singletonList(new String[]{"Role Name","Description"})