Create ArrayList from array

后端 未结 30 2259
遇见更好的自我
遇见更好的自我 2020-11-21 22:29

I have an array that is initialized like:

Element[] array = {new Element(1), new Element(2), new Element(3)};

I would like to convert this

30条回答
  •  执念已碎
    2020-11-21 23:01

    Java 9

    In Java 9, you can use List.of static factory method in order to create a List literal. Something like the following:

    List elements = List.of(new Element(1), new Element(2), new Element(3));
    

    This would return an immutable list containing three elements. If you want a mutable list, pass that list to the ArrayList constructor:

    new ArrayList<>(List.of(// elements vararg))
    

    JEP 269: Convenience Factory Methods for Collections

    JEP 269 provides some convenience factory methods for Java Collections API. These immutable static factory methods are built into the List, Set, and Map interfaces in Java 9 and later.

提交回复
热议问题