我想声明一个ArrayListtype int。
为什么以下给我一个错误:
ArrayList<int> list1 = new ArrayList<int>();
但以下工作:
ArrayList<Integer> list1 = new ArrayList<Integer>();
?
ArrayList只能引用类型,不能引用原语。Integer是一个类,而不是一个基元。
当您声明时ArrayList<Integer> list1 = new ArrayList<Integer>(),您正在创建一个ArrayList将存储Integer类型而不是int原语的。
如果您想了解原始类型和引用类型之间的区别,请查看http://pages.cs.wisc.edu/~hasti/cs302/examples/primitiveVsRef.html
因为int是原始类型。只有引用类型可以用作泛型参数。
简短的回答是泛型(like ArrayList<Integer>)不接受原始类型(int),只接受对象(Integer)。
这是因为类似的类ArrayList是使用对象实现的。由于每个类都继承自 Object,因此编译器可以插入其他类。但是原始类型(如int)不继承自 Object,因为它们不是类。因此,Sun/Oracle 开设了Integer课程来帮助解决这个问题。
所以,简而言之:int不是一个Object.
上面的所有答案都回答了为什么,但这个问题的根源是原始数据类型的频繁自动装箱和拆箱。IntBuffer 或 ChadBuffer 已经解决了这个问题,或者您将原始类型命名为它已经存在于 nio 文件夹中。下次如果你想使用原始 ArrayList 不要使用 List 而是使用 IntBuffer
int是一个primitive。它不是一个Object.
有关更多详细信息,请参阅此链接。
int 是原始数据类型,但 Integer 是一个类,因此 arrayList 数组只能将引用类型作为其参数,而不是原始类型
int 不是 Object,因此如果列表类型为 int,则无法完成列表的实现。