ArrayList initialization equivalent to array initialization

This question already has an answer here:

  • Create ArrayList from array 32 answers
  • Initialization of an ArrayList in one line 32 answers

  • Arrays.asList可以在这里帮助:

    new ArrayList<Integer>(Arrays.asList(1,2,3,5,8,13,21));
    

    Yes.

    new ArrayList<String>(){{
       add("A");
       add("B");
    }}
    

    What this is actually doing is creating a class derived from ArrayList<String> (the outer set of braces do this) and then declare a static initialiser (the inner set of braces). This is actually an inner class of the containing class, and so it'll have an implicit this pointer. Not a problem unless you want to serialise it, or you're expecting the outer class to be garbage collected.

    I understand that Java 7 will provide additional language constructs to do precisely what you want.

    EDIT: recent Java versions provide more usable functions for creating such collections, and are worth investigating over the above (provided at a time prior to these versions)


    Here is the closest you can get:

    ArrayList<String> list = new ArrayList(Arrays.asList("Ryan", "Julie", "Bob"));
    

    You can go even simpler with:

    List<String> list = Arrays.asList("Ryan", "Julie", "Bob")
    

    Looking at the source for Arrays.asList, it constructs an ArrayList, but by default is cast to List. So you could do this (but not reliably for new JDKs):

    ArrayList<String> list = (ArrayList<String>)Arrays.asList("Ryan", "Julie", "Bob")
    
    链接地址: http://www.djcxy.com/p/17626.html

    上一篇: 将数组转换为ArrayList

    下一篇: ArrayList初始化等同于数组初始化