Generic Introduction: the generic type added in JDK 5.0 is an important improvement in type security in Java. Generics are a major step towards type security in Java. The nature of generics is parameterized, that is, the operated data type is specified as a parameter. This type of parameter can be used to create classes, interfaces, and methods, which are called generic classes, generic interfaces, and generic methods.
General generic
Class point <t> {// you can write the private t var identifier here. // The VaR type is specified by T, that is, public t getvar () is specified externally () {// The type of the returned value is determined by the external return var;} public void setvar (T var) {// The type set is also determined by the external this. var = var ;}}; public class demo {public static void main (string ARGs []) {point <string> P = new point <string> (); // The VaR type is string type P. setvar ("it"); // set the string system. out. println (getvar (); // print string }};
If there is no generic type, the programmer must remember the object type and execute type conversion. In this case, the type conversion may fail.
Class Point {private string var; Public String getvar () {return var;} public void setvar (string var) {This. var = var ;}}; public class demo {public static void main (string ARGs []) {point P = new point (); p. setvar ("it"); system. out. println (INT) getvar (); // type conversion error }};
The use of generics saves some java conversions between types. Obviously, the main benefit of generics is that the compiler retains the type information of parameters, performs type checks, and performs type conversion operations: the compiler ensures that these types of conversions are absolutely correct.
Generic Array
Public class genericsdemo30 {public static void main (string ARGs []) {integer I [] = fun1 (1, 2, 3, 4 ); // returns the Generic Array fun2 (I);} public static <t> T [] fun1 (t... arg) {// receive variable parameter return ARG; // return Generic Array} public static <t> void fun2 (T Param []) {// output system. out. print ("receiving Generic Array:"); For (T: Param) {system. out. print (t + ",");}}};
Wildcard
Class info <t> {private t var; // defines the generic variable public void setvar (T var) {This. var = var;} public t getvar () {return this. vaR;} Public String tostring () {// print return this directly. var. tostring () ;}}; public class genericsdemo14 {public static void main (string ARGs []) {info <string> I = new info <string> (); // use string as the generic type I. setvar ("it"); // set the fun (I);} public static void fun (info <?> Temp) {// you can receive any generic object system. Out. println ("content:" + temp );}};