Java generics in-depth explanation

Source: Internet
Author: User

Reference: Java generics click to open link

Generics are checked at the first compile time , in order to avoid overloading that is caused only by inconsistent data types.

In the absence of generics, once an object is thrown into the Java collection, the collection forgets the object's type and treats all objects as object types.
When a program takes an object out of a collection, it requires a forced type conversion, which is not only bloated in code but also prone to classcastexception exceptions.
1. The classcastexception problem that occurs during the run time is solved by the compile time. It's safe to run.
2. Avoid the hassle of forced conversions

General generic class point<t>{//Here can be casually write the identification symbol, T is the type of the abbreviation for the private t var;//var is specified by T, i.e.: externally specified public T GetVar      () {//the type of the return value is determined by the external return var;      The type of public void SetVar (T var) {//set is also determined externally by This.var = var;  }  }; public class genericsdemo06{public static void Main (String args[]) {point<string> p = new Point<st Ring> ();        The var type inside is String type P.setvar ("it");   Sets the string System.out.println (P.getvar (). Length ());  Gets the length of the string}}; ----------------------------------------------------------class notepad<k,v>{//Specify two generic type private     K key;   The type of this variable is determined externally by private V value;      The type of this variable is determined externally by the public K GetKey () {return this.key;      } public V GetValue () {return this.value;      } public void Setkey (K key) {this.key = key;      public void SetValue (V value) {this.value = value;  }  }; public class Genericsdemo09{public static void Main (String args[]) {notepad<string,integer> t = null;       Defines an object of two generic types T = new notepad<string,integer> ();        The key inside is string,value for the integer T.setkey ("Tom");            Set the first content of T.setvalue (20);      Set a second content System.out.print ("name;" + T.getkey ());       Obtain information System.out.print (", age;" + t.getvalue ());  Get information}};     Wildcard class info<t>{private T var;      Defines a generic variable public void SetVar (T var) {this.var = var;      } public T GetVar () {return this.var;      } public String toString () {//Direct print return this.var.toString ();  }  }; public class genericsdemo14{public static void Main (String args[]) {info<string> i = new Info<stri       Ng> ();                            Use string for generic type I.setvar ("it");      Set content fun (i); } public static void Fun (Info<?> temp) {//can receive arbitrary generic object System.out.println ("content:" + temp);  }  };     Restricted generic class info<t>{private T var;      Defines a generic variable public void SetVar (T var) {this.var = var;      } public T GetVar () {return this.var;      } public String toString () {//Direct print return this.var.toString ();  }  }; public class genericsdemo17{public static void Main (String args[]) {info<integer> i1 = new Info<in        Teger> ();            A generic object that declares an integer info<float> i2 = new info<float> ();                                 Declares a generic object of float I1.setvar (30);                              Set integer, Auto boxing i2.setvar (30.1f);          Set decimal, Auto boxing fun (i1);      Fun (I2);  } public static void Fun (INFO&LT;? extends Number> temp) {//can only receive subclasses of number and its number System.out.print (temp      + ",");  }  }; //----------------------------------------------------------Class info<t>{private T var;      Defines a generic variable public void SetVar (T var) {this.var = var;      } public T GetVar () {return this.var;      } public String toString () {//Direct print return this.var.toString ();  }  }; public class genericsdemo21{public static void Main (String args[]) {info<string> i1 = new Info<str      Ing> ();      A generic object that declares a string info<object> i2 = new info<object> ();          A generic object that declares object I1.setvar ("Hello");          I2.setvar (New Object ());          Fun (I1);      Fun (I2); } public static void Fun (INFO&LT;? Super String> temp) {//can only receive generic System.out.print of type String or object (TEM      P + ",");  }  };     Generics cannot be transformed upward class info<t>{private T var;      Defines a generic variable public void SetVar (T var) {this.var = var;      } public T GetVar () {return this.var;     } public String toString () {//Direct printing     return this.var.toString ();  }  }; public class genericsdemo23{public static void Main (String args[]) {info<string> i1 = new Info<str      Ing> ();          The generic type is string info<object> i2 = null;                               I2 = I1;  This sentence will go wrong incompatible types}}; Generic interface interface info<t>{//define Generic public T GetVar () on interface,//define abstract method, the return value of abstract method is generic type} class Infoimpl&lt ;             T> implements info<t>{//defines the subclass of the generic interface as Private T var;        Define the property public Infoimpl (T var) {//Set property content This.setvar (Var) by constructing method;      } public void SetVar (T var) {this.var = var;      } public T GetVar () {return this.var;  }  };        public class genericsdemo24{public static void Main (String arsg[]) {info<string> i = null;  Declares the interface object i = new Infoimpl<string> ("Tom");      Instantiate an object by subclasses System.out.println ("content:" + I.getvar ()); }  }; ----------------------------------------------------------interface info<t>{//define generic public T GE on interface TVar ();                Defines the abstract method, the return value of the abstract method is the generic type} class Infoimpl implements info<string>{//defines the subclass of the generic interface private String var;        Defines the property public Infoimpl (String var) {//Set property content This.setvar (Var) by constructing the method;      } public void SetVar (String var) {this.var = var;      } public String GetVar () {return this.var;  }  };      public class genericsdemo25{public static void Main (String arsg[]) {Info i = null;    Declares the interface object i = new Infoimpl ("Tom");      Instantiate an object by subclasses System.out.println ("content:" + I.getvar ());  }  };                  Generic method class demo{public <T> t Fun (T-t) {//can receive any type of data return T;  Return the parameter directly}};   public class genericsdemo26{public static void Main (String args[]) {Demo d = new demo ();         Instantiating a Demo object String str = d.fun ("Tom");     Pass the string int i = D.fun (30);   Pass number, auto boxing System.out.println (str);     Output content System.out.println (i);  Output content}};     Returns a generic type instance through a generic method class Info<t extends number>{//Specifies the upper limit, only the number type private T var;         This type is determined externally by the public T GetVar () {return this.var;      } public void SetVar (T var) {this.var = var;          } public String ToString () {//overwrite the toString () method in the object class return This.var.toString ();  }  };          public class genericsdemo27{public static void Main (String args[]) {info<integer> i = fun (30);      System.out.println (I.getvar ()); } public static <t extends number> info<t> (T param) The generic type that is passed in or returned from the {///method is determined by the type of parameter that is set when the method is called info<      t> temp = new info<t> ();        Instantiate info Temp.setvar (param) Based on the data type passed in;   Set the passed content to the Var attribute of the Info object return temp;  Returns the instantiated object}}; UseGeneric Uniform incoming parameter type class info<t>{//Specify upper limit, can only be numeric type private T var;         This type is determined externally by the public T GetVar () {return this.var;      } public void SetVar (T var) {this.var = var;          } public String ToString () {//overwrite the toString () method in the object class return This.var.toString ();  }  }; public class genericsdemo28{public static void Main (String args[]) {info<string> i1 = new Info<str          Ing> ();          info<string> i2 = new info<string> ();        I1.setvar ("HELLO");       Set content I2.setvar ("Tom");      Set content Add (I1,I2); } public static <T> void Add (info<t> i1,info<t> i2) {System.out.println (I1.getvar () + ""      + I2.getvar ());  }  }; Generic array public class genericsdemo30{public static void Main (String args[]) {Integer i[] = fun1 (1,2,3,4,5,6)   ;      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 ("Receive generic array:");          for (t T:param) {System.out.print (t + ",");  }      }  };      Nested settings for generics class info<t,v>{//Receive two generic type private T var;      private V value;          Public Info (T var,v value) {This.setvar (VAR);      This.setvalue (value);      } public void SetVar (T var) {this.var = var;      public void SetValue (V value) {this.value = value;      } public T GetVar () {return this.var;      } public V GetValue () {return this.value;  }  };      Class demo<s>{private S info;      Public Demo (S info) {This.setinfo (info);      } public void SetInfo (S info) {this.info = info;      } public S GetInfo () {return this.info;  }  }; public class genericsdemo31{public static void MaIn (String args[]) {demo<info<string,integer>> d = null;   Use Info as the generic type of the demo info<string,integer> i = null;    INFO specifies two generic type I = new info<string,integer> ("Tom", 30); Instantiate Info Object d = new demo<info<string,integer>> (i);          Set the object of the info class in the Demo class System.out.println ("content one:" + d.getinfo (). GetVar ());      SYSTEM.OUT.PRINTLN ("Content two:" + D.getinfo (). GetValue ());  }  };


Java generics in-depth explanation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.