Java generics in-depth explanation

Source: Internet
Author: User

 Java generics 2011-09-13 16:09 58263 person reading Comments (6) Favorite report Javaclassintegerlistjdbc compiler 1. Overview before introducing paradigms, Java types are divided into primitive types, complex types, where complex types are divided into arrays and classes. Once the paradigm is introduced, a complex type can be subdivided into more types. For example, the original type List, which is now subdivided into list<object&gt, list<string> and so on more types. Note that now List<object> list<string> are two different types, with no inheritance between them, even if String inherits Object.    The following code is illegal for list<string> ls = new arraylist<string> (); list<object> lo = ls; The reason for this is that, depending on the LO declaration, the compiler allows you to add any object (such as an integer) to the lo, but this object is List<string&gt, which destroys the integrity of the data type. Before introducing the paradigm, to support multiple data types in a method in a class, you need to overload the method, and after introducing the paradigm, you can solve the problem (polymorphism) and further define the relationships between multiple parameters and the return value.  For example public void write (Integer i, integer[] ia);p ublic void Write (Double D, double[] da), the generic version is public <T> void write (T T, t[] ta); 2. The naming style for defining & using Type parameters is: It is recommended that you use a concise name as the name of the formal type parameter (if possible, a single character). It is best to avoid lowercase letters, which makes it easily distinguishable from other common form parameters. Use T to represent a type, no matter when it is more specific than the type to differentiate it. This is often seen in generic methods. If there are multiple types of parameters, we may use the adjacent letters of T in the alphabet, such as S. If a generic function appears inside a generic class, it is best to avoid confusion by using the same name in the type arguments of the method and the type parameters of the class.  The same is true for inner classes. 2.1 Defines a class with a type parameter when defining a class with a type parameter, specify the name of one or more type parameters in the <> immediately following the life of the class, and you can also qualify the range of values for the type parameter, separated by a number of type parameters.After you define the type parameters, you can use the type parameters almost anywhere (except static blocks, static properties, static methods, and so on), just as you would with a normal type. Note that the type parameters defined by the parent class cannot be inherited by the quilt class.  public class testclassdefine<t, S extends t> {...} 2.2 Define the type parameter method when defining a method with a type parameter, specify the first name of one or more type parameters after the visible range decoration (for example, public), and the value range of the type parameter, separated by a number of type parameters, in <>. After you define a type parameter, you can use the type parameter anywhere you define the method, just as you would with a normal type. For example: Public <t, S extends t> t Testgenericmethoddefine (T T, s s) {...} Note: Defines a method with type parameters, the main purpose of the ride is to express the relationship between multiple parameters and the return value. For example, in this example, the inheritance relationship between T and S, the type of the return value is the same as the value of the first type parameter. If you want to implement polymorphism only, use wildcard characters as a priority. The contents of the wildcard are shown in the following sections. Public <T> void TestGenericMethodDefine2 (list<t> s) {...} should be changed to public void TestGenericMethodDefine2 (LIST&L t;? > s) {...} 3. Type parameter assignment worth all type parameters are required when assigning values to the type parameters of a class or method.  Otherwise, you will get a compilation error. 3.1 Assigning a type parameter to a class with a type parameter assigns a type parameter to a class with a type parameter in two ways when a class variable is first declared or instantiated. For example list<string> List; List = new arraylist<string>; The second inheriting class or when implementing an interface.   For example public class Mylist<e> extends arraylist<e> implements list<e> {...} 3.2 When assigning a worth method to a type-parameter method, the compiler automatically assigns the type parameter when it cannot be successfully assigned to the Times compilation error. For example public &LT;T&GT T TestGenericMethodDefine3 (T T, list<t> List) {...} public <T> T testGenericMethodDefine4 (list<t> l  Ist1, list<t> list2) {...} Number n = null; Integer i = null; Object o = null; Testgenericmethoddefine (n, i);//T is number, S is integer testgenericmethoddefine (o, i),//t is object, S is integer list< Number> list1 = null; TestGenericMethodDefine3 (i, list1)//At this time t is number list<integer> list2 = null; TestGenericMethodDefine4 (List1, List2)//Compile Error 3.3 Wildcard in the above two sections, the type parameter is given a specific value, in addition to this, you can also assign an indeterminate value to the type parameter. For example list<?> unknownlist; list<? Extends number> unknownnumberlist; list<?  Super Integer> Unknownbaselineintgerlist; Note: In the Java Collection framework, for a container class with an unknown type for the parameter value, only the element can be read, and the element cannot be added, because its type is unknown, so the compiler does not recognize that the type of the element being added and the type of the container are compatible, the only exception being null list<string > liststring; list<?> unknownList2 = liststring; Unknownlist = UnknownList2; liststring = unknownlist;//Compilation error 4. An array pattern can declare an array using a class with a generic parameter value, but cannot create an array list<integer>[] ilistarray; New arraylist<integer>[10];//CompilationError 5. Implementation principle 5.1. Java paradigm Compile-time technology that does not contain the generic information at run time, only the class instance contains the definition information for the type parameter. Generics are implemented through front-end processing of the Java compiler called erase (Erasure). You can (basically) think of it as a source-to-source conversion that transforms the generic version into a non-generic version. Basically, wiping out all the generic type information. All type information between the angle brackets is thrown away, so for example a list<string> type is converted to a list. All references to type variables are replaced with the upper bound of the type variable (usually object).       Also, whenever the result code type is incorrect, a conversion to the appropriate type is inserted. <T> t Badcast (T T, Object O) {return (t) o;//Unchecked warning} type parameter does not exist at run time. This means that they do not add any time or space burden, which is good. Unfortunately, this also means that you cannot rely on them for type conversions.       5.2. What is the result of a generic class that is shared by all its calls to print the following code?       list<string> L1 = new arraylist<string> ();       list<integer> L2 = new arraylist<integer> (); System.out.println (l1.getclass () = = L2.getclass ()); Maybe you can say false, but you're wrong. It prints out true. Because all instances of a generic class have the same runtime class (class) at run time, regardless of their actual type parameters. In fact, generics are called generics because they have the same behavior for all of their possible type parameters, and the same classes can be treated as many different types. As a result, the static variables and methods of a class are also shared among all instances. This is why it is not legal to use a type parameter (the type argument is a specific instance) in a static or static initialization code or when declaring and initializing a static variable.       5.3. Another implication of the transformation and instanceof generic classes being shared by all their instances (instances) is that it is meaningless to check whether an instance is a generic class of a particular type.   Collection cs = new arraylist<string> ();    if (CS instanceof collection<string>) {...}//illegal similar, type conversion collection<string> CStr = (collection<stri ng>) CS; Get a unchecked warning because the runtime environment does not check for you. 6. Class Paradigm after Java 5, class becomes generic. A change in JDK1.5 is that the class Java.lang.Class is generic. This is an interesting example of extending generics beyond the container class. Now that class has a type parameter T, you'll probably ask, what does t mean? It represents the type represented by the class object. For example, the String.class type represents class<string>,serializable.class on behalf of Class<serializable>. This can be used to improve the type safety of your reflection code. In particular, because the class's newinstance () method now returns a T, you can get a more precise type when you create an object with reflection. For example, suppose you want to write a tool method for a database query, given an SQL statement, and return a collection of objects in the database that meet the query criteria (collection). One method is to explicitly pass a factory object, like the following code: interface factory<t> {public t[] make ();} Public <T> collection<t> Select (factory<t> Factory, String statement) {collection<t> Resul       t = new arraylist<t> (); /* Run SQL query using JDBC */for (int i=0; i<10; i++) {/* iterate over JDBC results */T item = f            Actory.make (); /* Use reflection and set all of the item ' s fields from SQL results */Result.add (item); } return result;        You can call this: select (new Factory<empinfo> () {public empinfo make () {return new Empinfo (); }}, "Selection string"), or you can declare a class empinfofactory to support the interface Factory:class Empinfofactory implements FACTORY&LT;EMPINFO&G T {... public empinfo make () {return new Empinfo ();}} Then invoke: Select (Getmyempinfofactory (), "selection string"); The disadvantage of this solution is that it requires one of the following: The lengthy anonymous factory class at the call, Or declaring a factory class for each type you want to use and passing its objects to the calling place that's not natural. Using the class type parameter value is very natural and can be used by reflection. Code that does not have generics may be: Collection Emps = Sqlutility.select (Empinfo.class, "select * from Emps");    ... public static Collection select (Class C, String sqlstatement) {Collection result = new ArrayList ();        /* Run SQL query using JDBC */for (/* Iterate over JDBC results */) {Object item = c.newinstance ();    /* Use reflection and set all of the item ' s fields from SQL results */RESULT.ADD (item); } return result; But that doesn't give us a set of exact types we want to return. Now that class is generic, we can write: Collection<emPinfo> Emps=sqlutility.select (Empinfo.class, "select * from Emps"); ... public static <T> collection<t> Select (class<t>c, String sqlstatement) {collection<t> ResU    lt = new arraylist<t> ();        /* Run SQL query using JDBC */for (/* Iterate over JDBC results */) {T item = c.newinstance ();    /* Use reflection and set all of the item ' s fields from SQL results */RESULT.ADD (item); } return result; To get the collection we want in a type-safe way. This technique is a very useful technique and it has become a customary usage that is widely used in the new API for processing annotations (annotations). 7. New and old code compatible with 7.1. In order to ensure the compatibility of the code, the following code compiler (JAVAC) allows, type safety has your own guarantee list L = new arraylist<string> (); list<string> L = new ArrayList (); 7.2. When upgrading your class library to a generic version, use the covariant return value sparingly.    For example, put code public class Foo {public Foo Create () {return new Foo ();    }}public class Bar extends Foo {public Foo Create () {return new Bar ();    }} using the covariant return value style, change Bar to public class Bar extends Foo {public Bar Create () {return new Bar (); Be careful with the clients of your class library. 8. Reference HTTP://JAVA.SUn.com/j2se/1.5/pdf/generics-tutorial.pdf 

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.