为什么不能为泛型自动填充Java基本类型? [英] Why not auto-box Java primitive types for Generics?
问题描述
据我了解,您提出的 ArrayList< int>
将与 ArrayList< Integer>
相同。是对的吗? (换句话说,在内部它仍然存储一个Integer;每次你把东西放进去或者把它拿出来,它会自动地对它进行box / unbox,但是autoboxing / autounboxing已经为 ArrayList< Integer> )
如果它是相同的,那么我不明白具有重复语法< int>
表示与< Integer>
相同的内容。 (实际上它会引入额外的问题,因为例如 int []
与 Integer []
,所以如果你有 T []
,并且 T
是 int
,这是什么意思?)
Java does not allow primitive types to be used in generic data structures. E.g. ArrayList<int> is not allowed. The reason is, primitive types can not be directly converted to Object. However Java 1.5 does support auto-boxing, and wrapper classes work in generic data structures. So why couldn't the compiler auto-box it to ArrayList<Integer>? Are there any other reasons for why this can not work?
So as far as I understand it, your proposed ArrayList<int>
would be identical to ArrayList<Integer>
. Is that right? (In other words, internally it still stores an Integer; and every time you put something in or get it out, it would automatically box/unbox it, but autoboxing/autounboxing already does that for ArrayList<Integer>
.)
If it is the same, then I don't understand what is the utility of having a duplicate syntax <int>
that means the same thing as <Integer>
. (In fact it will introduce additional problems, because for example int[]
is not the same runtime type as Integer[]
, so if you have T[]
, and T
is int
, what would it mean?)
这篇关于为什么不能为泛型自动填充Java基本类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!