Java high-tech generic

Source: Internet
Author: User

I. Origins of generics

  • What are the problems in the collection classes before JDK 1.5?

Arraylist collection = new arraylist ();
Collection. Add (1 );
Collection. Add (1l );
Collection. Add ("ABC ");
Int I = (integer) collection. Get (1); // type conversion is required during compilation and an error occurs during runtime!

  • The Collection class of JDK 1.5 requires that you specify the type of data to be loaded into the collection when defining the collection, and cannot add data other than the specified type.

Arraylist <integer> collection2 = new arraylist <integer> ();
Collection2.add (1 );
/* Collection2.add (1l );
Collection2.add ("ABC"); * // The two lines of code report a syntax error during compilation.
Int I2 = collection2.get (0); // type conversion is not required.

  • Generics are provided for the javac compiler. They can limit the input type in the set and prevent the compiler from inputting illegal data in the source program, the "type" information will be removed when the compiler compiles a set with the type description, so that the program running efficiency is not affected. For parameterized generic types, getclass () the Return Value of the method is exactly the same as that of the original type. The bytecode generated by compilation removes generic type information. If you can skip the compiler, you can add other types of data to a generic set. For example, you can use reflection to obtain a set, call the add method.
Ii. Generic
  • Arraylist <E> class definition and arraylist <integer> class reference involve the following terms:

This is called the arraylist <E> generic type.
E In arraylist <E> is called a type variable or a type parameter.
The entire arraylist <integer> is called a parameterized type.
An integer in arraylist <integer> is an instance of the type parameter or an actual type parameter.
In arraylist <integer>, <> Read typeof
Arraylist is called the original type.

  • Compatibility between parameterized types and original types:

A parameterized type can reference an object of the original type and compile a report warning, for example, collection <string> C = new vector (); // OK
The original type can reference an object of parameterized type and compile a report warning. For example, collection C = new vector <string> (); // the original method accepts a set parameter, the new type must also be passed into the generic type. The type parameters strictly describe what data types are loaded in the set and what types of data can be added. Remember: collection <string> and collection <Object> are two parameterized types without conversion relationships. If the vector <string> V = new vector <Object> (); is acceptable, the objects retrieved from V will be used as strings, V can actually point to any type of objects. Assume that vector <Object> V = new vector <string> (); If yes, in the future, you can add any type of object to V, and only string type objects can be loaded in the set actually pointed by V.

  • Parameterized types do not consider the inheritance relationship of type parameters:

Vector <string> V = new vector <Object> (); // error! /// Do not write <Object> yes. If you write it, it is a known object.
Vector <Object> V = new vector <string> (); // error!
The compiler cannot create arrays of generic variables. That is, when creating an array instance, the array elements cannot use parameterized types. For example, the following statement has an error:
Vector <integer> vectorlist [] = new vector <integer> [10];

  • Question: Will the following code report an error? No error is reported.

Vector V1 = new vector <string> ();
Vector <Object> V = V1; // compilation is OK, and an error occurs during running! Iii. wildcard:
Define a method to print all data in a set of any parametric types. How can this method be defined?
Error Method:
Public static void printcollection (collection <Object> Cols ){
For (Object OBJ: Cols ){
System. Out. println (OBJ );
}
/* Cols. Add ("string"); // Yes
Cols = new hashset <date> (); // an error is reported! */
}
Correct method:
Public static void printcollection (collection <?> Cols ){
For (Object OBJ: Cols ){
System. Out. println (OBJ );
}
// Cols. Add ("string"); // error, because it does not know its future match must be string
Cols. Size (); // yes, this method is irrelevant to the type parameter.
Cols = new hashset <date> ();
}
Summary:
Use? Wildcards can reference other parameterized types ,? Variables defined by Wildcards are mainly used as references. You can call Methods unrelated to parameterization, rather than methods related to parameterization.

Public static void printcollection (collection <?> Cols) {// Col. add ("123"); error. Type-related operation is not supported. out. println ("Size:" + cols. size (); For (Object OBJ: Cols) {system. out. println (OBJ);} Cols = new hashset <date> (); // It is OK}

4. What about generic? Wildcard Extension

  • Limit the upper boundary of a wildcard:

Correct: vector <? Extends number> X = new vector <integer> ();
Error: vector <? Extends number> X = new vector <string> ();

  • Limit the bottom boundary of a wildcard:

Correct: vector <? Super integer> X = new vector <number> ();
Error: vector <? Super integer> X = new vector <byte> ();
Tip:

  • A limited wildcard always includes itself .? It can only be used as a reference and cannot be used to assign values to other variables.

Vector <? Extends number> Y = new vector <integer> ();
Vector <number> X = y;
The code above is incorrect. The principle is similar to that of vector <Object> X11 = new vector <string> (). Values can only be assigned by force type conversion. 5. generic methods Java generic methods do not have powerful C ++ template functions, and the following code in Java cannot be compiled:
<T> t add (t x, t y ){
Return (t) (x + y );
// Return NULL;
}
The angle brackets used to place generic type parameters should appear after all the modifiers of the method and before the return type of the method, that is, before the return value. By convention, type parameters are usually represented by a single uppercase letter.
Syntax of the generic method for exchanging the positions of two elements in an array is defined as follows:
Static <E> void swap (E [] A, int I, Int J ){
E t = A [I];
A [I] = A [J];
A [J] = T;
} // Or use an interview question: reversing the order of elements in an array
Only the reference type can be used as the actual parameter of the generic method. Swap (New int [3], 3, 5); the statement reports a compilation error.
In addition to the extends qualifier, you can also use the extends qualifier when defining generics, for example, the definition of the class. getannotation () method. You can use & to specify multiple boundaries, such as <v extends serializable & cloneable> void method (){}
Generic types can be used in common methods, constructor methods, and static methods.
You can also use type variables to indicate exceptions, which are called parameterized exceptions. They can be used in the throws list of methods, but not in catch clauses.
You can have multiple types of parameters in the generic type. Separate them with commas (,) in the angle brackets that define them. For example:
Public static <K, V> V getvalue (K key) {return map. Get (key );}

/* 1. The generic type (or generic type) in Java is similar to the template in C ++. However, this similarity is limited to the surface. in Java, generics are basically implemented in the compiler, used by the compiler to perform type checks and type inference, and then generate common non-generic bytecode, this implementation technique is called Erasure (the compiler uses generic type information to ensure type security and then clears bytecode before it is generated ). This is because extended virtual machine instruction sets to support generics are considered unacceptable, which creates insurmountable obstacles for Java vendors to upgrade their JVM. Therefore, Java generics use the erasure method that can be fully implemented in the compiler. For example, the compiler reports an error in the following two methods, which are not considered to be two different parameter types but the same parameter type. Private Static void applygeneric (vector <string> V) {} Private Static void applygeneric (vector <date> V) {} */Private Static <t> void applygeneric (vector <t> V ){}
// Use the following code to explain how to use generics for exceptions: Private Static <t extends exception> sayhello () throws t {try {} catch (exception e) {Throw (t) E ;}}

Public static <t> T autoconverttype (Object OBJ) // compile a generic method to automatically convert objects of the object type to other types. {Return (t) OBJ ;}// test code: // object xxx = "ABC"; // string YYY = autoconverttype (XXX); // define a method, you can fill all elements in an array of any type into an object of the corresponding type. Public static <t> T [] fill (T [] A, t v) {for (INT I = 0; I <. length; I ++) A [I] = V; return a;} public static <E> void printcollection (collection <E> Cols) {// use the custom generic method to print all content in a set of any expected parameterized types. For (e obj: Cols) {system. out. println (OBJ) ;}}/* defines a method to securely copy data from a set of any parameter types to an array of the corresponding types? The generic method must be used for definition. If the following form is used: static void copy (collection A, object [] B ); otherwise, data of type A may be copied to an array of type B. The generic method is defined as static <t> void copy (collection <t> A, T [] B );*/
6. type inference
  • The process of determining the actual type parameter of the canonicalized method by the interpreter is called type inference. The method of realizing the type inference is a very complicated process compared with perceptual inference.
  • The rule is as follows:

When a type variable is only applied to one of all parameters and return values in the entire parameter list, it is determined based on the actual application type at the time of calling the method, this is easily inferred by feeling, that is, the type of the generic parameter is directly determined based on the type or return value of the parameter passed when the method is called. For example:
Swap (New String [3], 3,4) static <E> void swap (E [] A, int I, Int J)
When a type variable is applied to multiple parameters and return values in the entire parameter list, if the actual application types in multiple parameters correspond to the same type when calling the method, this is easily inferred by feeling, for example:
Add (3, 5) static <t> t add (t a, t B)
When a type variable is applied in multiple places of all parameters and return values in the entire parameter list, if the actual application types in multiple places correspond to different types when the method is called, and no return value is used, at this time, the maximum intersection type among multiple parameters is obtained. For example, the actual type of the following statement is number. Compilation is okay, but there is a problem during running:
Fill (new integer [3], 3.5f) static <t> void fill (T [] A, t v)
When a type variable is applied in multiple places of all parameters and return values in the entire parameter list, if the actual application types in multiple places correspond to different types when the method is called, and the return value is used, at this time, the type of the returned value is given priority. For example, if the actual type of the following statement is integer, an error will be reported during compilation. Change the type of variable X to float, and compare the error message reported by eclipse, then, change the X type of the variable to number. The error is not returned:
Int x = (3, 3.5f) static <t> t add (t a, t B)

  • The type inference of the parameter type is passed. In the first case below, it is inferred that the actual parameter type is object, and there is no problem in compilation, in the second case, the type variable is directly determined as the string type based on the parameterized Vector class instance, and the compilation will fail:

Copy (new integer [5], new string [5]) static <t> void copy (T [] A, T [] B );
Copy (new vector <string> (), new integer [5]) static <t> void copy (collection <t> A, T [] B ); 7. If multiple instance objects of a class use the same generic parameter, that is, when the generic type referenced in these areas must be of the same actual type, in this case, the generic type is used for definition, that is, the generic type at the class level. The syntax format is as follows:
Public class genericdao <t> {
Private t field1;
Public void save (t obj ){}
Public t getbyid (int id ){}
}
Class-level generic variables are parameterized Based on the type information specified when the class name is referenced. For example, either of the following methods can be used:
Genericdao <string> Dao = NULL;
New genericdao <string> ();
Note:
When you parameterize a generic type, the instance of the type parameter must be a reference type, not a basic type.
When a variable is declared as a generic type, it can only be called by instance variables, methods, and internal classes, rather than static variables and static methods. Because static members are shared by all parameterized classes, static members should not have class-level type parameters.
Q: Is there only one method in a class that requires generics? Is it class-level generics or method-level generics? (Method-level)

// Define a persondao object and a person object in a non-generic way first. After writing the object, let us know that there are many entity types in a project and a lot of Dao needs to be written, is there any good way? // Generic class: Class genericdao <t> {public void save (t) {} public void Delete (int id) {} public void Update (t) {} public t findbyid (int id) {return NULL;} public set <t> findbyconditions (string conditions) {return NULL ;}}
8. obtain generic parameterized types through reflection
// Sample code: Class genericalreflection {private vector <date> dates = new vector <date> (); Public void setdates (vector <date> dates) {This. dates = dates;} public static void main (string [] ARGs) {method methodapply = genericalreflection. class. getdeclaredmethod ("applygeneric", vector. class); parameterizedtype ptype = (parameterizedtype) (methodapply. getgenericparametertypes () [0]; system. out. println ("setdates (" + (class) ptype. getrawtype ()). getname () + "<" // obtain the original parameter type + (class) (ptype. getactualtypearguments () [0]). getname () // obtain the actual parameter type date + ">)") ;}// application of generic Dao: public abstract class daobaseimpl <t> implements daobase <t> {protected class <t> clazz; Public daobaseimpl () {type = This. getclass (). getgenericsuperclass (); parameterizedtype Pt = (parameterizedtype) type; this. clazz = (class) pt. getactualtypearguments () [0]; system. out. println ("clazz =" + this. clazz) ;}} public class articledaoimpl extends daobaseimpl <Article> implements articledao {}

Other code:

Import Java. util. *; public class generictest {public static void main (string [] ARGs) throws exception {// check the generic parameter type for the compiler's arraylist list1 = new arraylist (); list1.add (1); arraylist <integer> list2 = new arraylist <integer> (); list2.add (3); // system. out. println (list2.get (0 ). getclass (); // class Java. lang. integer system. out. println (list1.getclass () = list2.getclass (); // outputs true. list1 and list2 use the same bytecode. // reflection can bypass compilation. List2.getclass (). getmethod ("add", object. class ). invoke (list2, "Java"); system. out. println (list2.get (1); system. out. println ("--------------------------------"); printcollection (list2); // you only need to remember that the range received by the parameter type on the left must be greater than or equal to the vector on the right <? Extends number> Y = new vector <integer> (); // vector <number> X = y; error vector <number> X = new vector <number> (); y = x; system. out. println (New arraylist <integer> (). getclass (). getname (); system. out. println (New arraylist <string> (). getclass (). getname (); // traverses the map set Map <string, integer> map = new hashmap <string, integer> (); map. put ("James", 23); map. put ("Li Si", 24); map. put ("Wang Wu", 33); set <map. entry <string, inte GER> entryset = map. entryset (); // use foreach to traverse for (map. entry <string, integer> entry: entryset) {system. out. println (entry. getkey () + "-->" + entry. getvalue ();} // another way to traverse iterator <map. entry <string, integer> it = entryset. iterator (); While (it. hasnext () {map. entry <string, integer> entry = it. next (); system. out. println (entry. getkey () + "" + entry. getvalue ();} number X1 = add (4, 6.3); // 4 automatically loads object X2 = Add (3, "AA"); swap (New String [] {"A", "B", "C"}, 1, 2 ); // swap (New int [] {1, 3, 5, 9}, 1, 3); error! Int is a basic type and cannot be used in generic parameters. out. println (convert ("fjdks"); system. out. println (convert (123);} // defines a method that can fill all elements in an array of any type into an object of the corresponding type. Public static <t> T [] fill (T [] A, t obj) {for (INT I = 0; I <. length; I ++) {A [I] = OBJ;} return a;} // compile a generic method to automatically convert objects of the object type to other types. Public static <t> T convert (Object OBJ) {return (t) OBJ ;} // public static <t> void swap (T [] A, int X, int y) {T temp = A [x]; A [x] = A [y]; A [y] = temp;} public static <t> t add (t x, t y) {return NULL ;} public static void printcollection (collection <?> Cols) {// Col. add ("123"); error. Type-related operation is not supported. out. println ("Size:" + cols. size (); For (Object OBJ: Cols) {system. out. println (OBJ);} Cols = new hashset <date> (); // It is OK} Private Static <t> void applygeneric (vector <t> V ){}}

How do I know under what circumstances can I use generics? In this case, the class can be parameterized only when the class is defined as a generic type.

Use the following code to check that the "type" information has been removed from the results returned by the getclass () method.
System. Out. println (New arraylist <integer> (). getclass (). getname ());
System. Out. println (New arraylist <string> (). getclass (). getname ());

The second line of code in the main method of the following program is exactly the same as the two lines of code in the annotation. The two lines of code in the annotation cannot be compiled, and the second line (using the method call chain) but it can be compiled smoothly.
Public class test
{
Public void func ()
{
System. Out. println ("func ");
}
 
Public static void main (string ARGs []) throws exception
{
Object OBJ = new test ();

// The following line can be compiled successfully
(TEST) OBJ). getclass (). newinstance (). func ();

// The following two rows cannot be compiled
/* Class C = (TEST) OBJ). getclass ();
C. newinstance (). func ();*/

}
}
Because of generic, the compiler can obtain type information during compilation, so this type of code can be compiled. Change the following two lines
Class <? Extends test> C = (TEST) OBJ). getclass ();
C. newinstance (). func ();
It should be able to pass the compilation.

After the model is introduced in JDK 1.5, the object. getclass () method is defined as follows:
Public final class <? Extends Object> getclass ()
This indicates that the object type returned by (TEST) OBJ). getclass () Statement is class <? Extends test>, while the newinstance () method of class <t> is defined as follows:
Public t newinstance () throws instantiationexception, illegalaccessexception
That is, for the compiler, the object type of the newinstance () method of class <Test> is test, and (TEST) OBJ). getclass () returns the object type as class <? Extends test>. Therefore, the compiler considers the object type returned by (TEST) OBJ). getclass (). newinstance () as test.

The following two lines of code cannot be compiled
Class C = (TEST) OBJ). getclass ();
C. newinstance (). func ();
It is because (TEST) OBJ). getclass () returns the object type as class <? Extends test>, But we forcibly convert the result into a class in the first line, and then call the newinstance method of the class, instead of calling the newinstance method of the class <Test>, of course, the compiler no longer considers the newinstance method of class to return the object test.

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.