Generics are only valid at compile time

import java.util.ArrayList;
public class Test {
public static void main(String []args) {
ArrayList<String> a = new ArrayList<String>(); //Create a generic
ArrayList b = new ArrayList();  
Class c1 = a.getClass(); //get generic type
Class c2 = b.getClass();  
System.out.println(c1 == c2); //output true
}
}

The above example can prove that the program will take measures to de-genericize after compilation. That is to say, generics in Java are only valid at the compile stage. During the compilation process, after the generic result is correctly checked, the relevant information of the generic will be erased, and the method of type checking and type conversion will be added at the boundary of the object entering and leaving the method. That is, generic information does not enter the runtime phase.

This can be summed up in one sentence: Generic types are logically viewed as multiple different types, which are actually the same basic type.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325370974&siteId=291194637