Why can't I have 'int' as the type of an ArrayList?

前端 未结 7 711
时光取名叫无心
时光取名叫无心 2020-12-05 06:17

I want to declare an ArrayList of type int.

Why does the following give me an error:

ArrayList list1 = new Array         


        
相关标签:
7条回答
  • 2020-12-05 06:59

    Because int is a primitive type. Only reference types can be used as generic parameters.

    0 讨论(0)
  • 2020-12-05 07:10

    ArrayList can only reference types, not primitives. Integer is a class, not a primitive.

    When you declare ArrayList<Integer> list1 = new ArrayList<Integer>(), you're creating an ArrayList which will store the Integer type, not the int primitive.

    If you want to read about the difference between primitive and reference types, check out http://pages.cs.wisc.edu/~hasti/cs302/examples/primitiveVsRef.html

    0 讨论(0)
  • 2020-12-05 07:11

    int is not an Object and hence if list type is int, implementations of the list cannot be done.

    0 讨论(0)
  • 2020-12-05 07:13

    All the answers above answer why but the root of this question is frequent auto boxing and unboxing of the primitive data types. This problem is already solved by IntBuffer or ChadBuffer or you name the primitive type it's already there in the nio folder. Next time if you want to use primitive ArrayList don't use List instead use IntBuffer

    0 讨论(0)
  • 2020-12-05 07:14

    The short answer is that generics (like ArrayList<Integer>) do not accept primitive types (int), only objects (Integer).

    This is because classes like ArrayList are implemented as using Objects. Since every class inherits from Object, the compiler can just plug in other classes. But primitive types (like int) do not inherit from Object, for they are not classes. So, Sun/Oracle made the Integer class to help with this.

    So, in short: int is not an Object.

    0 讨论(0)
  • 2020-12-05 07:19

    int is a primitive data type but Integer is a class so an arrayList array can only take reference types as its parameter not primitive type

    0 讨论(0)
提交回复
热议问题