Before Java SE 1.5, in the absence of generics, the parameter "arbitrary" was realized by reference to the type Object. The disadvantage of "arbitrary" was to do explicit mandatory type conversion , and this The conversion is required when the developer can predict the actual parameter type. For the case of forced type conversion errors, the compiler may not prompt the error, and the exception occurs only at runtime, which is a safety hazard.
public class Gen <T> { private T ob; // Define generic member variables public Gen (T ob) { this .ob = ob; } public T getOb () { return ob; } public void setOb (T ob) { this .ob = ob; } public void showType () { System.out.println ( "The actual type of T is:" + ob.getClass (). getName ()); } }
public class GenDemo { public static void main (String [] args) { // Define an Integer version of the generic class Gen Gen <Integer> intOb = new Gen <Integer> (88 ); intOb.showType (); int i = intOb.getOb (); System.out.println ( "value =" + i); System.out.println ( "----------------------- ----------- " ); // Define a String version of the generic class Gen Gen <String> strOb = new Gen <String> (" Hello Gen! " ); StrOb.showType (); String s = strOb.getOb(); System.out.println("value= " + s); } }
In a word
, the benefit of generics is that type safety is checked at compile time , and all coercion is automatic and implicit , which improves the code reuse rate and does not have to be forced like Object.