简体   繁体   English

实例化泛型类的JAVA数组

[英]Instantiating JAVA Array of Generic Class

E[] arr = (E[])new Object[INITIAL_ARRAY_LENGTH];

The code above was taken from this following post: 上面的代码是从取以下职位:

Where E is a generic class type. 其中E是泛型类。 How does the compiler/JVM know how much memory it needs to assign when we are using type Object to instantiate the array. 当我们使用对象类型实例化数组时,编译器/ JVM如何知道需要分配多少内存。 My understanding is, type casting only allows to change reference type, but not the underlying object structure. 我的理解是,类型转换只允许更改引用类型,但不允许更改底层对象结构。

An array of a certain size of reference type will take same size in memory no matter what types of objects it holds. 某种大小的引用类型的数组将在内存中占据相同的大小,而不管它持有什么类型的对象。 This is because the memory holds only the references (pointers) and that's it and not the memory for the array items which is assigned when those objects are created. 这是因为内存只保存引用(指针),而不是创建这些对象时分配的数组项的内存。 The heap will then hold new objects as they're created and assigned to the array. 然后,堆将在创建新对象并将其分配给数组时保留它们。

So, the following arrays will all take up the same size: 因此,以下数组将占用相同的大小:

new Integer[10]
new BigInteger[10]
new String[10]
new Object[10]

Note that to the compiler, an array of a non-constrained generic type translates to an array of Object. 请注意,对于编译器,非约束通用类型的数组会转换为Object的数组。

Also note that arrays of primitives likely have a different memory footprint. 另请注意,基元数组可能具有不同的内存占用。

..... .....

Again, this is just the memory for the array itself, not the items it references -- and this is a very important point in all of this, probably the most important point for understanding this. 同样,这只是数组本身的内存, 而不是它引用的项目 - 这是所有这一点中非常重要的一点,可能理解这一点最重要的一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM