Why use generics
It is required to design a class that represents a coordinate point, which consists of X and Y.
Coordinate representation method:
Integer: x=10,y=20;
Decimals: x=10.5,y=20.6
String: x= "longitude 180 degrees", y= "latitude 30 degrees"
Ask, how this kind of design.
Problem analysis
Be sure to design the class that represents the coordinate point. Class Name: Point.
But the coordinates of X, y save three types of data (int,float,string), to use a class can receive these three types at the same time, you can now only use the object class, because object can accept any type of
Data, it will automatically change upward . The following transformations occur for three data types:
numbers (int), auto-Boxed (Integer), The object is shifted up to receive a decimal point ( float)----auto-boxing (float)--- Upward Transformation Object receive string (string),up-conversion object receive
Point class:
classpoint{PrivateObject x;//represents the x-coordinate PrivateObject y;//represents the y-coordinate Public voidSetX (Object x) { This. x =x; } Public voidsety (Object y) { This. y =y; } PublicObject GetX () {return This. x; } PublicObject GetY () {return This. Y; }};
The overall code is as follows: You need to be aware of automatic boxing and automatic unboxing for up and down transitions.
classpoint{PrivateObject x;//represents the x-coordinate PrivateObject y;//represents the y-coordinate Public voidSetX (Object x) { This. x =x; } Public voidsety (Object y) { This. y =y; } PublicObject GetX () {return This. x; } PublicObject GetY () {return This. Y; }}; Public classgenericsdemo01{ Public Static voidMain (String args[]) {point P=NewPoint ();//object that declares a pointP.setx (10);//Take advantage of auto-boxing operations: int ------and ObjectP.sety (20);//take advantage of auto-boxing operations: int ------and Object intx = (Integer) p.getx ();//Remove data first into Integer, then automatically unpack, Integer-->int inty = (Integer) p.gety ();//remove data first to integer, then automatically unpackSystem.out.println ("Integer representation, X coordinate:" +x); System.out.println ("Integer representation, y-coordinate:" +y); }};
The above code is a big problem, the addition of the data type in the conversion, then the automatic unpacking operation is necessary to modify the forced transformation code.
Understanding Generics
when a class is declared, an identity is used to represent the type of a property in a class or the return value of a method and the type of the parameter. This allows the class to be declared and instantiated as long as you specify the type you want to use.
Generic definition instance:
class point<t>{ // here can be casually write the logo symbol, T is the type of the abbreviation private T var; // the type of 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; } Public The type of void SetVar (T var) { // Set is also determined externally by this . var = var; }};
In conjunction with one of the above complete examples:
classpoint<t>{//Here you can write the symbol, T is the abbreviation of type PrivateT var;//the type of VAR is specified by T, i.e.: externally specified PublicT GetVar () {//the type of the return value is determined externally returnvar; } Public voidSetVar (T var) {//the type of setting is also determined externally This. var =var; }}; Public classgenericsdemo06{ Public Static voidMain (String args[]) { point<String> p =NewPoint<string> ();//the var type inside is String typeP.setvar ("Mldn");//Set StringSystem.out.println (P.getvar (). Length ());//gets the length of the string }};
You can better protect your data types.
The previous program can be modified directly by generics.
The result of the modification is as follows:
classPoint<t>{ PrivateT x;//represents the x-coordinate PrivateT y;//represents the y-coordinate Public voidSetX (T x) { This. x =x; } Public voidsety (T y) { This. y =y; } PublicT GetX () {return This. x; } PublicT GetY () {return This. Y; }}; Public classgenericspoint{ Public Static voidMain (String args[]) { point<Integer> p =NewPoint<integer>() ; P.setx (10);//take advantage of auto-boxing operations: int --and IntegerP.sety ("Latitude 210 degrees");//take advantage of auto-boxing operations: int --and Integer intx = P.getx ();//Automatic Unpacking inty = p.gety ();//Automatic UnpackingSystem.out.println ("Integer representation, X coordinate:" +x); System.out.println ("Integer representation, y-coordinate:" +y); }};
In such a program, the operation of type conversion is reduced (instead of being defined in a class with an object class, you do not have to shift up, down, down, unboxing, boxing).
Using generics in construction methods
generics can also be used in construction methods, and it is generally possible to assign a value to a property in a class for a construction method .
To assign a value instance to a constructor method property:
classpoint<t>{//Here you can write the symbol, T is the abbreviation of type PrivateT var;//the type of VAR is specified by T, i.e.: externally specified Public point (T var) {//Set content by construction method This. var =var; } PublicT GetVar () {//the type of the return value is determined externally returnvar; } Public voidSetVar (T var) {//the type of setting is also determined externally This. var =var; }}; Public classgenericsdemo08{ Public Static voidMain (String args[]) { point<String> p =Newpoint<String> ("mldn") ;//the var type inside is String typeSystem.out.println ("Content:" +P.getvar ()); }};
Specify two generic types, as follows:
classnotepad<k,v>{//two generic types are specified here PrivateK key;//The type of this variable is determined externally PrivateV value;//The type of this variable is determined externally PublicK GetKey () {return This. Key; } PublicV GetValue () {return This. Value; } Public voidSetkey (K key) { This. Key =key; } Public voidSetValue (V value) { This. Value =value; }}; Public classgenericsdemo09{ Public Static voidMain (String args[]) {Notepad<String,Integer> T =NULL;//to define an object of two generic typest =NewNotepad<string,integer> ();//The key inside is string,value as an integerT.setkey ("Li Xinghua");//set the first contentT.setvalue (30);//set a second contentSystem.out.print ("name;" + T.getkey ());//Get informationSystem.out.print (", age;" + t.getvalue ());//Get information }};
Security warnings for generics
In a generic application, it is best to specify the data type of the class object when declaring it. For example: "Info<string>", but you can also specify no type.
PackageThread1;classInfo<t>{ PrivateT var; PublicT GetVar () {return This. var; } Public voidSetVar (T var) { This. var =var; } PublicString toString () {//overwrite the ToString () method in the object class return This. var.tostring (); }}; Public classdemo1{ Public Static voidMain (String args[]) { Info i = new Info (); Warning, no generic type specified I.setvar ("mldn"); Set StringSystem.out.println ("Content:" +I.getvar ()); }};
Operation Result:
Content: MLDN
The program does not affect execution, but the generic type is not specified in the info class, and the T is automatically set to the object type in Java in order to ensure that the program can still run. This allows you to accept arbitrary data types.
That is, the Var type at this point is object, and all generic information will be erased.
The above procedure is equivalent to the following definition:
classInfo<t>{ PrivateT var; PublicT GetVar () {return This. var; } Public voidSetVar (T var) { This. var =var; } PublicString toString () {//overwrite the ToString () method in the object class return This. var.tostring (); }}; Public classgenericsdemo11{ Public Static voidMain (String args[]) { Info <Object> i = new info<object> (); Specifies that object is a generic type I.setvar ("Mldn"); Set StringSystem.out.println ("Content:" +I.getvar ()); }};
Getting Started with generics