Creating a new ArrayList in Java

后端 未结 9 1740
执念已碎
执念已碎 2021-02-05 00:31

Assuming that I have a class named Class,

And I would like to make a new ArrayList that it\'s values will be of type Class.

My question

9条回答
  •  孤城傲影
    2021-02-05 00:52

    Java 8

    In order to create a non-empty list of fixed size where different operations like add, remove, etc won't be supported:

    List fixesSizeList= Arrays.asList(1, 2);
    

    Non-empty mutable list:

    List mutableList = new ArrayList<>(Arrays.asList(3, 4));
    

    Java 9

    With Java 9 you can use the List.of(...) static factory method:

    List immutableList = List.of(1, 2);
    
    List mutableList = new ArrayList<>(List.of(3, 4));
    

    Java 10

    With Java 10 you can use the Local Variable Type Inference:

    var list1 = List.of(1, 2);
    
    var list2 = new ArrayList<>(List.of(3, 4));
    
    var list3 = new ArrayList();
    

    Check out more ArrayList examples here.

提交回复
热议问题