简体   繁体   中英

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. How does the compiler/JVM know how much memory it needs to assign when we are using type Object to instantiate the array. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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