Learning GoalsMastering the meaning of generics. Master the basic use of generics. Learn about generic warning messages and generic erase patterns.
generics are additions after JDK1.5, generics (Generic)reasons for using generics
Topic Analysis:The first thing to consider is that you must create a class--point that represents the coordinate point, where two properties are used to represent the x and Y coordinates, but there are three types of integers (int, float, String) that are stored in X and Y, good one. To use a type to receive three types of data at the same time, you can now use object only, because the object class can receive any type of data, and the upward transformation occurs automatically, so that three types of data are installed in the following ways:numbers (int), automatically boxed into interger-> upward transformation using object receivedecimal (float), automatically boxed into float-> upward transformation using object receivestring--upward transformation using object receive
designing a Point class
Class Point{private object x;//represents the x-coordinate private Object y;//represents the y-coordinate public void SetX (Object x) {this.x = x;} public void Sety (Object y) {this.y = y;} Public Object GetX () {return this.x;} Public Object GetY () {return this.y;}}; public class Genericsdemo01{public static void Main (String args[]) {point P = new Point ();//Declares an object of point P.setx (10);//Use Auto-boxing operations: INT------objectp.sety (20);//Take advantage of auto-boxing: INT----and Objectint x = (integer) p.getx (); The data is removed first into an integer, then automatically unpacking int y = (integer) p.gety ();//The data is first changed to an integer, then automatically unpacking System.out.println ("Integer representation, X coordinate:" + x); System.out.println ("Integer representation, y-coordinate:" + y);}};
Decimal notation
Class Point{private object x;//represents the x-coordinate private Object y;//represents the y-coordinate public void SetX (Object x) {this.x = x;} public void Sety (Object y) {this.y = y;} Public Object GetX () {return this.x;} Public Object GetY () {return this.y;}}; public class Genericsdemo02{public static void Main (String args[]) {point P = new Point ();//Declares an object of point P.setx (10.5f);// Take advantage of auto-boxing: float--------objectp.sety (20.6f);//Take advantage of auto-boxing: float-------objectfloat x = (float) p.ge TX ();///The data is first changed to float, then automatically unpacking float y = (float) p.gety ();//The data is first changed to float, then automatically unpacking System.out.println ("decimal notation, X coordinate:" + x); System.out.println ("decimal notation, y-coordinate:" + y);}};
string representation:
Class Point{private object x;//represents the x-coordinate private Object y;//represents the y-coordinate public void SetX (Object x) {this.x = x;} public void Sety (Object y) {this.y = y;} Public Object GetX () {return this.x;} Public Object GetY () {return this.y;}}; public class Genericsdemo03{public static void Main (String args[]) {point P = new Point ();//Declares an object of point P.setx ("180 degrees east longitude") ;//String--and Objectp.sety ("Latitude 210");//String--objectstring x = (string) p.getx ();//The data is first changed to a String and then automatically disassembled Strin G y = (string) p.gety ();//The data is first changed to a string, then automatically unpacking System.out.println ("string representation, X coordinate:" + x); System.out.println ("string representation, y-coordinate:" + y);}};
There is a big problem with the above code, if you now assume the following program code.
Class Point{private object x;//represents the x-coordinate private Object y;//represents the y-coordinate public void SetX (Object x) {this.x = x;} public void Sety (Object y) {this.y = y;} Public Object GetX () {return this.x;} Public Object GetY () {return this.y;}}; public class Genericsdemo04{public static void Main (String args[]) {point P = new Point ();//Declares an object of point P.setx (10);//Use Auto-boxing operations: INT-----and Objectp.sety ("Latitude 210");//String--Objectint x = (Integer) p.getx ();//data is first changed to Integ Er, then automatically unpacking int y = (integer) p.gety ();//The data is first changed to integer, then automatically unpacking System.out.println ("Integer representation, X coordinate:" + x); System.out.println ("Integer representation, y-coordinate:" + y);}};
The traditional method of implementation is likely to be improper operation of the situation, this program is the data type is not unified caused. Understanding Genericsuse of genericsgenerics solve the security problems of data types, and the main principle is to represent the type of a property in a class or the return value of a method and the type of the parameter at the time of class declaration. This allows the class to be declared or instantiated as long as the desired type is specified. the definition format for generics is as follows:[access rights] class name < generic type 1, generic type 2,...... Generic type 3>{ [Access] generic type identity variable name; [Access] Generic type identity method name () {}; [Access] return value type declares method name (generic type identity variable name) {}; }definition of generic objectClass Name < concrete type > Object name = new class name < concrete type > ();
define a point class in this format.
Class point<t>{//here can be casually write the symbol, T is the type of the abbreviation private T var;//var is specified by T, that is: the external specified public T GetVar () {//Return value type is determined by the outside return var;} The public void SetVar (T var) {//set type is also determined externally by This.var = var;}};
Once you have finished, you can use it when you declare the object.
Class point<t>{//here can be casually write the symbol, T is the type of the abbreviation private T var;//var is specified by T, that is: the external specified public T GetVar () {//Return value type is determined by the outside return var;} The public void SetVar (T var) {//set type is also determined externally by This.var = var;}}; public class Genericsdemo06{public static void Main (String args[]) {point<string> p = new point<string> ();// The Var type of the polygon is the string type P.setvar ("mldn");//sets the string System.out.println (P.getvar (). Length ());
The above is to set the var variable to a string type, and of course can be set to an integer, if the content of the set is inconsistent with the specified generic type, the error will occur at compile time.
Class point<t>{//here can be casually write the symbol, T is the type of the abbreviation private T var;//var is specified by T, that is: the external specified public T GetVar () {//Return value type is determined by the outside return var;} The public void SetVar (T var) {//set type is also determined externally by This.var = var;}}; public class Genericsdemo07{public static void Main (String args[]) {point<integer> p = new point<integer> (); /the var type is string type P.setvar ("mldn");//Set String}};
This will better protect the data type. generics allow you to modify the previous program directly.
Class Point<t>{private T X;//represents the x-coordinate private T y;//represents the y-coordinate public void SetX (T x) {this.x = x;} public void Sety (T y) {this.y = y;} Public T GetX () {return this.x;} Public T GetY () {return this.y;}}; public class Genericspoint{public static void Main (String args[]) {point<integer> p = new point<integer> ();p. SetX (10);//Use Auto-boxing operations: INT---integerp.sety (20);//Take advantage of auto-boxing: INT--and Integerint x = P.getx ();//auto-unpacking int y = p.gety ( );//Auto-unpacking System.out.println ("Integer representation, X coordinate:" + x); System.out.println ("Integer representation, y-coordinate:" + y);}};
In such a program, reducing the operation code of the class type conversion, and more secure, if the content set is not a number, it will be compiled at the time of the error, as follows:
Class Point<t>{private T X;//represents the x-coordinate private T y;//represents the y-coordinate public void SetX (T x) {this.x = x;} public void Sety (T y) {this.y = y;} Public T GetX () {return this.x;} Public T GetY () {return this.y;}}; public class Genericspoint{public static void Main (String args[]) {point<integer> p = new point<integer> ();p. SetX (10);//Use Auto-boxing operations: INT-to-integerp.sety ("Latitude 210");//Take advantage of auto-boxing operation: INT---Integerint x = P.getx ();//auto-unpacking int y = P . GetY ();//Automatic Unpacking System.out.println ("Integer representation, X coordinate:" + x); System.out.println ("Integer representation, y-coordinate:" + y);}};
Generics can also be used in construction methods, and it is generally possible to use construction methods to assign values to properties in a class.using generics in construction methodsA construction method can initialize a property in a class, so if a property in a class is specified by a generic and needs to be constructed to set the property content, then the definition of the constructed method is not the same as it was before, and you do not need to specify the generic as the Declaration class. Use format:[access Rights] construction method ([< generic type > Parameter name]) {}For example:
Class point<t>{//here can be casually write the symbol, T is the name of the type of the private t var;//var is specified by T, that is: the external specified public point (T var) {// Set content by construction method This.var = var;} Public T GetVar () {//the type of the return value is determined by the external return var;} The public void SetVar (T var) {//set type is also determined externally by This.var = var;}}; public class Genericsdemo08{public static void Main (String args[]) {point<string> p = new Point<string> (" Liuxun ");//The var type is string type System.out.println (" content: "+ P.getvar ());}};
You can also specify multiple generics in a generic type. set multiple generics with the following example:
Class notepad<k,v>{//here specifies two generic types private k key;//The type of this variable is externally determined by private V value;//The type of this variable is externally determined by public K GetKey () {retur n 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 two generic type objects t = new notepad<string,integer> ();//The key inside is string,value for Integert.setkey ("刘勋");//Set the first content T.setvalue (22);// Set the second content System.out.print ("name;" + T.getkey ());//obtain Information System.out.print (", age;" + t.getvalue ());//Obtain information}};
security warnings for genericsIn a generic application, it is a good idea to specify the type of data inside the class object when declaring it, such as "info<string>", but you can also specify no type.
Class Info<t>{private t var;p ublic 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 Genericsdemo10{public static void Main (String args[]) {Info i = new Info ();//warning, no generic type I.setvar ("MLDN") specified;// Set string System.out.println ("content:" + I.getvar ());}};
The type of the generic is not specified in the info class, and in Java in order to ensure that the program can still be used, T is set to the object type, so that you can receive any data type, that is, the type of Var is object, all the generic information will be erased, in fact , the above procedure is equivalent to the following definition format:
Class Info<t>{private t var;p ublic 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 Genericsdemo11{public static void Main (String args[]) {info<object> i = new info<object> ();//Specify O Bject is a generic type I.setvar ("mldn");//Set string System.out.println ("content:" + I.getvar ());}};
Security warnings for genericsIn a generic application, it is best to specify the data type of the class when declaring it, for example: "Info<string>", but you can also specify no type, so that when the user uses such a class, an unsafe warning message appears, such as:
Summary:1, the production of generic meaning: In order to ensure the security of data. 2, the basic use of generics, by the external specified its specific operation type.
Introduction and simple use of generics in Java