Creating a new ArrayList in Java

后端 未结 9 1742
执念已碎
执念已碎 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:51

    You're very close. Use same type on both sides, and include ().

    ArrayList<Class> myArray = new ArrayList<Class>();
    
    0 讨论(0)
  • 2021-02-05 00:52

    You are looking for Java generics

    List<MyClass> list = new ArrayList<MyClass>();
    

    Here's a tutorial http://docs.oracle.com/javase/tutorial/java/generics/index.html

    0 讨论(0)
  • 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<Integer> fixesSizeList= Arrays.asList(1, 2);
    

    Non-empty mutable list:

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

    Java 9

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

    List<Integer> immutableList = List.of(1, 2);
    
    List<Integer> 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<String>();
    

    Check out more ArrayList examples here.

    0 讨论(0)
  • 2021-02-05 00:53

    If you just want a list:

    ArrayList<Class> myList = new ArrayList<Class>();
    

    If you want an arraylist of a certain length (in this case size 10):

    List<Class> myList = new ArrayList<Class>(10);
    

    If you want to program against the interfaces (better for abstractions reasons):

    List<Class> myList = new ArrayList<Class>();
    

    Programming against interfaces is considered better because it's more abstract. You can change your Arraylist with a different list implementation (like a LinkedList) and the rest of your application doesn't need any changes.

    0 讨论(0)
  • 2021-02-05 01:04

    Do this: List<Class> myArray= new ArrayList<Class>();

    0 讨论(0)
  • 2021-02-05 01:05
        ArrayList<Class> myArray = new ArrayList<Class>();
    

    Here ArrayList of the particular Class will be made. In general one can have any datatype like int,char, string or even an array in place of Class.

    These are added to the array list using

        myArray.add();
    

    And the values are retrieved using

        myArray.get();
    
    0 讨论(0)
提交回复
热议问题