1. covariance of Arrays
Covariant refers:
If the Base class is the Base class of Sub, Base [] is the Base class of Sub.
While generics are immutable (invariant), ListIt will not be the base class of the List, nor its subclass.
ArrayCovarianceSome errors may occur, such as the following code:
public static void main(String[] args) { Object[] array = new String[10]; array[0] = 10; }
It can be compiled, because the array is covariant, and the Object [] type reference can point to a String [] type Object.
However, the following exception is reported during running:
Exception in thread "main" java.lang.ArrayStoreException: java.lang.Integer
However, this will not happen to generics:
public static void main(String[] args) { List< Object> list = new ArrayList< String>(); list.add(10); }
This Code cannot be compiled.
2. Specify the array.
Arrays are embodied (reified), while generics are erased at runtime (erasure ).
The array determines the type constraints of array elements only at runtime,
On the contrary, during runtime, the generic type information will be erased, and the type will be enhanced only during compilation.
Therefore, in the above example, the array method will report an ArrayStoreException at run time, and the generic type cannot be compiled at all.
3. generics are not covariant.
Although it is helpful to regard the set as an array abstraction, the array also has some special properties that the set does not have.
Arrays in Java are covariant. That is to say, if Integer is extended by Number (as is true), not only Integer is Number, but Integer [] is also Number []. you can pass the Number [] or assign it to Integer []. (More formally, if Number is an Integer supertype, Number [] is also an Integer [] supertype ).
You may think this principle applies to the generic type -- List Yes List In the List Place to pass List . Unfortunately, this is not the case.
There is a good reason why this is not allowed:
This will destroy the type security generic type to be provided.
If you can Assigned to List .
The following code allows non-Integer content to be placed in the List
List
li = new ArrayList
();List
ln = li; // illegalln.add(new Float(3.1415));
Because ln is a List , So adding Float to it seems completely legal. However, if ln is the alias of li, this destroys the type security commitment contained in the li definition-it is an integer list, which is why generic types cannot be changed together.