Why generic arrays are forbidden in Java

Steven Devin 2022-06-23 18:45:38 阅读数:515


First of all, understand two concepts .

1. Covariant array (covariant array)

stay Java in , array It's co denaturing .

Co denaturation means that , One The type is T[ ] The array of can contain , The type is T Elements or subtype The type is T The elements of .

So we can do this :

Number[] numbers = newNumber[3];
numbers[0] = newInteger(10);
numbers[1] = newDouble(3.14);
numbers[2] = newByte(0);

More Than This , If S yes T Of subtype, One type is S[ ] The array of is also a type T [ ] Array of subtype. for example Integer yes Number Of Subtype, We can do that :

Integer[] myInts = {
Number[] myNumber = myInts;

What if you do this ? No direct assignment through type objects .

myNumber[0] = 3.14;

The above code directly to The type is T[ ] Array assignment of , There is no problem during compilation ,

But if you run this code , An error warning will be raised ArrayStoreException.

This is because in the Operation period ,Java Know that this array is instantiated as an integer array .

2. Type Erasure (type erasure)

stay Java In the generic , A generic type is a type information , And is discarded by the compiler after compilation .

So generic type information , It does not exist during operation .

This process is called 「 Type Erasure 」.

// for example :
//Java Is an object-oriented language , All the elements are in Java Are associated with classes and objects .
//Java Of Object Class is the parent of all classes .
// therefore 
𝚂𝚝𝚛𝚒𝚗𝚐[ ] yes 𝙾𝚋𝚓𝚎𝚌𝚝[] Of subtype
but 𝚂𝚝𝚊𝚌𝚔<𝚂𝚝𝚛𝚒𝚗𝚐> No 𝚂𝚝𝚊𝚌𝚔<𝙾𝚋𝚓𝚎𝚌𝚝> Of subtype

in addition , Generics have no covariance .

3. Why is generic arrays forbidden ?

Continue with the previous example :

// Because of type erasure , Generic types during runtime ,Stack Of String The type will be erased to Stack.
// be-all Stack Generic types share the same Stack.class
// But in the array , Different types of arrays have their own class.
// Combine the covariance of the array , Even though 1. Medium No direct assignment through type objects .
// We can fool the compiler temporarily during compilation , But during operation ,Java Know what we're doing ,
// That is, the type of the array cannot be erased during runtime , This contradicts the type erasure of generics , therefore Java Generic arrays are prohibited in .
版权声明:本文为[Steven Devin]所创,转载请带上原文链接,感谢。 https://javamana.com/2022/174/202206231744550156.html