Initialization of an ArrayList in one line

后端 未结 30 2256
北恋
北恋 2020-11-22 01:10

I wanted to create a list of options for testing purposes. At first, I did this:

ArrayList places = new ArrayList();
places.add(\         


        
30条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-22 01:42

    In Java, you can't do

    ArrayList places = new ArrayList( Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));
    

    As was pointed out, you'd need to do a double brace initialization:

    List places = new ArrayList() {{ add("x"); add("y"); }};
    

    But this may force you into adding an annotation @SuppressWarnings("serial") or generate a serial UUID which is annoying. Also most code formatters will unwrap that into multiple statements/lines.

    Alternatively you can do

    List places = Arrays.asList(new String[] {"x", "y" });
    

    but then you may want to do a @SuppressWarnings("unchecked").

    Also according to javadoc you should be able to do this:

    List stooges = Arrays.asList("Larry", "Moe", "Curly");
    

    But I'm not able to get it to compile with JDK 1.6.

提交回复
热议问题