Create a List of primitive int?

后端 未结 10 1938
夕颜
夕颜 2020-11-27 12:43

Is there a way to create a list of primitive int or any primitives in java like following?

List myList = new ArrayList();
10条回答
  •  一向
    一向 (楼主)
    2020-11-27 12:55

    In Java the type of any variable is either a primitive type or a reference type. Generic type arguments must be reference types. Since primitives do not extend Object they cannot be used as generic type arguments for a parametrized type.

    Instead use the Integer class which is a wrapper for int:

    List list = new ArrayList();
    

    If your using Java 7 you can simplify this declaration using the diamond operator:

    List list = new ArrayList<>();
    

    With autoboxing in Java the primitive type int will become an Integer when necessary.

    Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes.

    So the following is valid:

    int myInt = 1;
    List list = new ArrayList();
    list.add(myInt);
    
    System.out.println(list.get(0)); //prints 1
    

提交回复
热议问题