1 PackageThinkinginjava;2 /*3 * Simulated Erase4 */5 Public classSimpleholder {6 7 PrivateObject obj;8 Public voidset (Object o) {9obj =o;Ten } One PublicObject Get () { A returnobj; - } - Public Static voidMain (string[] args) { the //if the class uses a generic parameter, and the type of the obj variable is the type represented by the generic parameter, the type information is automatically erased when the object of the class is constructed. - //for variable types with non-generic upper bounds converted to corresponding non-generic upper bounds, no specified is converted to object -Simpleholder demo =NewSimpleholder (); - //the compiler throws all of the type information at run time, so the set method parameter does not work even if the generic is used. + //Instead, it converts the converter to a non-generic upper bound, but when the object enters (through a generic set value) The object is judged to be consistent with the generic -Demo.set ("xxx") ; + //Of course, the obtained value is also the corresponding non-generic upper bound type. But the compiler will automatically insert code that enforces type conversions AString x =(String) demo.get (); at } -}
Package thinkinginjava;/* * Use generic version */public class Genericholder<t> {private T obj;p ublic void set (T t) {this.obj = t;} Public T get () {return obj;} public static void Main (string[] args) {genericholder<string> demo = new genericholder<string> ();//demo.set (New Object ()); Although all type information is dropped at run time, the compiler will still ensure that the arguments passed in are consistent with the generic Demo.set ("Hello"); String x = Demo.get (); The compiler automatically inserts a forced type conversion code when it comes out}}
About the Java Erase feature