public class Plate<T> {
private T item;
public Plate(T t){
item=t;
}
public void set(T t){
item=t;
}
public T get(){
return item;
}
public static void main(String[] args) {
Plate<String> [] arr=new Plate[10];
//Plate<String> [] arr2=new Plate<>[10];//
Plate<Integer> plate=new Plate<>(1);
Object[] arr1=arr;
arr1[0]=plate;
String a=arr[0].get();
}
}
May I ask why
Plate < String > [] arr=new Plate [10]
do not report an error, but
Plate < String > [] arr2=new Plate < > [10]
compilation error,
What"s the difference between these two sentences?-follow-up supplement-
about
in generics instantiation of arrays of parametrized types are illegal.
this is how I understand it. Let me illustrate it with an example:
static void test() {
Pair<Integer,Integer>[] intPairArr = new Pair<Integer,Integer>[10] ; // error
addElements(intPairArr);
Pair<Integer,Integer> pair = intPairArr[1];
Integer i = pair.getFirst();
pair.setSecond(i);
}
static void addElements( Object[] objArr) {
objArr[0] = new Pair<Integer,Integer>(0,0);
objArr[1] = new Pair<String,String>("",""); // should fail with ArrayStoreException
}
if it is supported, when we call the addElements method, we convert it up to Object [] (the array supports covariant, so it is compiled), and when we continue to add elements, it will be compiled and passed, so that arrayStoreException,Java will introduce generics at run time, one of the most important points is that for security, runtime exceptions will be exposed at compile time. Avoid some exceptions that cannot be found during compilation because the array supports covariance. It can be said that the creation of an array of generic objects is not supported because of the covariant feature of the array.
and what is mentioned in the answer is that Java does not support generic arrays. It is easy to understand, for example:
T [] arr=new T[10];
here we assume that T is String, because the generics of Java use the erasure mechanism, which only works at compile time, and after compilation, T is converted to Object,. In fact, all the Object arrays are created, so it is obviously wrong to convert them to String through the bridge method, so the creation of generic arrays is not supported.
We can create generic arrays in a roundabout way, for example:
public T[] createArray(T[] arr){
T[] array= (T[]) new Object[arr.length];
for (int i = 0; i <arr.length ; iPP) {
array[i]=arr[i];
}
return array;
}
actually copy the passed-in generic array into the corresponding Object array.
Last question, what causes Java to support array covariance, a potentially problematic feature?