What is the shortest way to initialize List of strings in java?

后端 未结 7 924
无人共我
无人共我 2020-12-04 17:39

I am searching for the shortest way (in code) to initialize list of strings and array of strings, i.e. list/array containing \"s1\", \"s2\", \"s3\" string elements.

7条回答
  •  长情又很酷
    2020-12-04 18:17

    Java 9+

    Java 9 introduces a convenience method List.of used as follows:

    List l = List.of("s1", "s2", "s3");
    

    Java 8 and older

    Here are a few alternatives:

    // Short, but the resulting list is fixed size.
    List list1 = Arrays.asList("s1", "s2", "s3");
    
    // Similar to above, but the resulting list can grow.
    List list2 = new ArrayList<>(Arrays.asList("s1", "s2", "s3"));
    
    // Using initialization block. Useful if you need to "compute" the strings.
    List list3 = new ArrayList() {{
        add("s1");
        add("s2");
        add("s3");
    }};
    

    When it comes to arrays, you could initialize it at the point of declaration like this:

    String[] arr = { "s1", "s2", "s3" };
    

    If you need to reinitialize it or create it without storing it in a variable, you do

    new String[] { "s1", "s2", "s3" }
    

    If the string constants are may though, it would look like

    String[] arr = { "s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9", "s10",
                     "s11", "s12", "s13" };
    

    In these cases I usually prefer writing

    String[] arr = "s1,s2,s3,s4,s5,s6,s7,s8,s9,s10,s11,s12,s13".split(",");
    

提交回复
热议问题