Java Fundamentals Strengthening Summary (ii)--generics

Source: Internet
Author: User
Tags class definition map class type casting

First, experience the generic type

Problems in the collection class before JDK1.5--you can add an object of any type to the collection, such as the following code:

1 package cn.gacl.generic.summary; 2  3 import java.util.ArrayList; 4  5 public class Generictest {6      7 public     static void Main (string[] args) {8         /** 9          * Before generics are used ArrayList containers can store any type of object          */11         ArrayList collection1 = new ArrayList ();         Collection1.add (1);//Store Integer object         collection1.add (1L);//Store Long object         collection1.add ("XDP");// Store string Object         /**16          * This will report an exception: JAVA. Lang. Classcastexception:17          * JAVA. Lang. LONG cannot is CAST to JAVA. Lang. INTEGER18          *          */20         int i = (Integer) collection1.get (1);     }22}

The collection class after JDK1.5 wants you to explicitly indicate what type of data you want to load into the collection when you define the collection, and you cannot join data other than the specified type, such as the following code:

        /**         * Use generic qualification ArrayList containers can only store objects of String type         */        arraylist<string> collection2 = new arraylist<string > ();        Collection2.add ("Aloof pale Wolf");        Collection2.add (1);//error, because limit Collection2 can only store object of string class, cannot join integer type Object        //collection2.add (1L);//Error, Because the Collection2 only stores objects of the string class, it cannot be added to a long object        //Because an object of type string is already indicated in the collection, so there is no need to force the transformation of        string element here. Collection2.get (0);

Generics are provided to the Javac compiler to see, can limit the input types in the collection, let the compiler block illegal input in the source program, compiler compile with parameter type description of the collection will go to remove "type" information, so that the program runs unaffected, for parameterized generic type, The return value of the GetClass () method is exactly the same as the original type , because the compiled bytecode removes the generic type information, so as long as you can skip the compiler, you can add other types of data to a generic collection.

  For example, the following code demonstrates " using reflection to get a collection, and then calling the Add method to store a string object in a collection that can only store an integer object "

1 arraylist<integer> collection3 = new Arraylist<integer> (); 2//For parameterized generic types, the return value of the GetClass () method is exactly the same as the original Type 3 System.out.println (Collection3.getclass ());//Result: Java.util.ArrayList4 System.out.println (Collection3.getclass () = = Collection2.getclass ());//result for true5//use reflection to get the collection, and then call the Add method to store a string object in a collection that can only store an integer object 6 Collection3.getclass (). GetMethod ("Add", Object.class). Invoke (Collection3, "abc"); 7 System.out.println ( Collection3.get (0));//The result of the output is: ABC, which proves that the string object is actually stored in a collection that can only store an integer object

Note:

    1. Generics are the hardest part of all the new features of JDK1.5, when generics are not used, as long as the object, regardless of what type of object, can be stored in the same collection, using a generic collection, you can limit the elements in a collection to a specific type, so that only objects of the same type are stored in the collection, which is more secure, and when the slave-set When you get an object in a hop, the compiler knows the type of the object, and it is easier to do this without forcing the type conversion on the object.
    2. After JDK1.5, you can also put a variety of different types of data into the same collection in the same way, but at compile time a unchecked warning is reported
    3. Type parameters in generics strictly describe what data types are loaded in the collection and what types of data can be added, remembering that:collection<string> and collectin<object> are two parameterized types that do not have a conversion relationship
Second, understand the generic type

    • The following terms are involved in the Arraylist<e> class definition and the Arraylist<integer> class reference:
      • Whole called arraylist<e> generic type
      • E in arraylist<e> is called a type variable or type parameter
      • The entire arraylist<integer> is called a parameterized type
      • An Integer in arraylist<integer> is called an instance of a type parameter or an actual type parameter
      • The <> in arraylist<integer> is "typeof"
      • ArrayList called primitive types
    • The compatibility of the parameterized type with the original type:
      • A parameterized type can reference an object of the original type, and the compiler will report a warning, such as:collection<string> C = new Vector ();
      • The original type can refer to an object of a parameterized type, and the compiler will report a warning at compile time, for example: Collection c = new vector<string> ();
    • Parameterized types do not consider inheritance relationships for type parameters:
      • Vector<string> v = new vector<object> ();//error, syntax not passed
      • Vector<object> v = new vector<string> ();//error, syntax not passed

Assuming that vector<string> v = new vector<object>; is possible, then the object taken from V later is treated as a String, and the set that V actually points to can include any type of object.

Assuming that vector< object > v = new vector< string >; can then add any type of objects to V, and V actually points to a collection that can only have String types of objects

Think: Will the following code make an error? ( no error )

    • Vector v1 = new vector<string> ();//The object of a parameterized type can give a reference to the original type
    • Vector<object> v=v1;//A reference to a parameterized type can point to an object of the original type
C. wildcard characters in generics

Problem: Define a method that can print out all the data in a collection of arbitrary parameterized types, how is this method defined?

Definition of error:

1     /** 2      * The object in Collection<object> only indicates that the method received in the Collection<object> instance object is an object 3      * Collection<object> is a specific type, and new hashset<date> is a specific type, with no compatibility issues for both 4      * @param Collection 5 */      6 Public     static void Printcollection (Collection<object> Collection) {7 for         (Object obj:collection) {8             System.out.println (obj); 9         }         Collection.add ("abc");//Yes         collection=new hashset<date> ();//will report error     

The right definition:

1     /** here in the collection<?>? Indicates that any type parameter can be transmitted to 2      * collection<?> cols can match any parameterized type, but exactly what type to match, only later to know 3      * So cols=new arraylist<integer> and cols = new arraylist<string> can be 4      * but Cols.add ("abc") or Cols.add ( New Date ()) None 5      */6 public     static void Printcollection (Collection<?> Collection) {7 for         (Object obj: Collection) {8             System.out.println (obj), 9         }10         //collection.add ("abc");//Error, Because collection do not know that the future matches must be string type one         collection.size ();//No error, this method is not related to the parameter type         collection=new hashset< Date> ();//This is possible. 13     

Summary: Wildcard characters can be used to refer to various other parameterized types,? Wildcard-defined variables are primarily used as references, you can call methods that are not parameter-independent, and you cannot invoke parameters-related methods

Iv. expansion of wildcard characters in generics

1. Limit the upper boundary of a wildcard?

    • The correct wording: vector<? extends number> x = new vector<integer> ();

What do you mean by this? The parameterized type represented must inherit the number class, as shown here? The integer type represented is the inheritance of the number class.

    • The wrong wording: vector<? extends number> x = new vector<string> ();

2. Limit the bottom boundary of the wildcard character?

    • The correct wording: vector<? Super Integer> y = new vector<number> ();

What does this mean? The parameterized type represented must be the parent class of the integer class, as shown here? The type of number represented is the parent of the integer class

    • The wrong wording: vector<? Super Integer> y = new vector<byte> ();
V. General application of Generics
 1 package cn.itcast.day2; 2 import java.util.HashMap; 3 import java.util.HashSet; 4 import Java.util.Map; 5 Import J Ava.util.Set; 6/** 7 * This class is used to demonstrate the application of generics 8 * 9 * @author aloof Wolf Ten * */12 public class Genericcase {public static void main (St Ring[] args) {hashmap<string, integer> maps = new hashmap<string, integer> (), Maps.put ("l HM "," Maps.put "," FLX ", 33); 17/**18 * Variable naming tips: If you don't know how to name a variable later, you can name it in the form of a method name, 19 * AS  If you do not know how to define a variable name at this time, you define the variable to receive the return value, and it is defined directly as ReturnValue20 */21 set<map.entry<string, integer>> entryset = Maps.entryset ();//The variable name here is defined directly as a method name 22//using the enhanced for loop iteration of key and Value23 in the map container//The entry here is an inner class of the map class, stored in the map class Both the key and the value are encapsulated in the Entry inner class 24//This Entry inner class provides the Getkey method to remove the key, the GetValue method takes out the value for (map.entry<string, integer& Gt Entry:entryset) {System.out.println (Entry.getkey () + ":" + entry.getvalue ()),}28}29}

It is also often used in JSP pages to iterate over a set or map collection using iteration labels <c:forEach>:

1 <c:foreach items= "${map}" var= "entry" >2        ${entry.key}:${entry.value}3 </c:forEach>
Vi. Custom Generic methods
 1 package cn.itcast.day2; 2 Import java.io.Serializable;  3/** 4 * This class is used to demonstrate how to define and use a generic method of 5 * 6 * @author aloof Wolf 7 * 8 * * 9 public class Genericmethod {ten public static void Main (string[] args) {One Add (3, 5); x1 = Add (3.5, 5);//The intersection of the integer type and the double type is the number class, and the number class is the two Class, you can define a variable of type number to receive the return value of x2 = Add (3, "abc");//The intersection of the integer type and the string type is the object class, because the object class is the parent class of all classes, so you can set the  A variable of type/**15 * Swap (new string[]{"abc", "123", "XDP"},1,2) to receive the return value, the result of the execution is as follows: * ABC 123 XDP * ABC XDP 12318 * From the result, the element with index 1 and the element with index 2 is indeed the swap position of */20 swap (new string[] {"abc", " 123 "," XDP "}, 1, 2);//Call a custom generic method, the actual argument passed in must be an array of reference type//swap (new int[]{1,2,3,4,5},1,3), or only the reference type can be used as the actual parameter of the generic method, where I         The nt[] array is a primitive type and cannot be used as a parameter to a generic method, so it will be an error PrintArray (new integer[]{1,2,3});//You can pass in an array of type Integer, because an array of type integer is 23 of the reference type      PrintArray (New int[]{10,2,5}); Cannot pass in an array of non-reference types as the actual parameter of the generic method 24}25/**26* Definition syntax for generic methods: This is defined as the return value type of a generic method method is T, that is, the specific type of any type return value is determined by the passed-in type parameter. * @param <t>29 * represents         Arbitrary type * @param x31 * @param y32 * @return33 */34 private static <T> t Add (t X, t y) {35 return null;36}37/**38 * Defines a generic method to swap two elements at a specified index in an array the incoming array can be an array of any type 39 * The actual parameter type of the incoming generic method must be an array of reference types , cannot be an array of basic types. * @param <t>42 * @param a43 * @param i44 * @param j45 */46 priv Ate static <T> void Swap (t[] A, int i, int j) {47//The print result of the element position in the array is not swapped printArray (a); t         EMP = a[i];50 A[i] = a[j];51 A[j] = temp;52 System.out.println (); 53//The element position in the array after the exchange of results 54 PrintArray (a); 55}56/**57 * Defines the method for printing arbitrary reference array types. * @param <t>60 * @param array */62 private static <T> void PrintArray (t[] array) {for (T T:array) {System.  Out.print (t + "t"); 65       }66}67/**68 * Defines a extends qualifier, and a generic method with multiple upper bounds, each boundary is delimited by the & symbol * @param <t>70 */71 Public <t extends Serializable & cloneable> void Method () {}72}

Common methods, construction methods, and static methods can all use generics

Vii. practice exercises of generic methods
    1. Write a generic method that automatically converts object type objects to other types
    2. Defines a generic method that fills all elements of an array of any type into an object of the appropriate type
    3. A custom generic method is used to print all the contents of a collection of arbitrary parameterized types.
    4. Defines a generic method that securely copies data from a collection of arbitrary parameter types into an array of the appropriate type
    5. Defines a generic method that securely copies data from an array of any parameter type to another array of the appropriate type
 1/** 2 * 1. Write a generic method to automatically convert object type objects to other types 3 * @param <T> 4 * @param obj 5 * @return 6 */7 private static <T> t autoconvert (Object obj) {8 return (t) obj; 9}10/**11 * 2. Defines a generic method that can be Fills all elements of an array of any type into an object of the corresponding type. * @param <t>13 * @param array14 * @param obj15 */16 Private STA          Tic <T> void Fillarray (t[] array,t obj) {+ for (int i=0;i<array.length;i++) {array[i]=obj;19 }20 PrintArray (array); 21}22/**23 * 3. Print out all the contents of any parameterized type in the form of a custom generic method. * @param <t& GT;25 * @param collection26 */27 private static <T> void Printcollection (collection<t> collectio N) {System.out.println (Collection.size ()); for (Object obj:collection) {System.out.printl n (obj); 31}32}33/**34 * 4. Define a generic method that securely copies data from a collection of arbitrary parameter types into an array of the appropriate type. * @param <t>36 *  @param srcCollection37    * @param descArray38 */39 private static <T> void Collectioncopytoarray (collection<t> srccollecti         On,t[] descarray) {iterator<t> it = srccollection.iterator (); int recordelementpostion=0;42         while (It.hasnext ()) {descarray[recordelementpostion]=it.next (); recordelementpostion++;45      }46 PrintArray (Descarray); 47}48/**49 * 5. Define a generic method that securely copies data from an array of any parameter type to another array of the corresponding type 50 * @param <t>51 * @param srcArray52 * @param descArray53 */54 private static <T> void Srcar Raytodescarray (t[] srcarray,t[] descarray) {(int i=0;i<srcarray.length;i++) {DESCARRAY[I]=SR carray[i];57}58 PrintArray (descarray);}60 private static <T> void PrintArray (t[] array) {T:array (t) {System.out.print (t + "\ n"); 63}64}
VIII. Custom generic Classes

If there are multiple instances of the class that use the same generic parameter, that is, if the generic type referenced in these places is to remain the same actual type, then the generic type is defined, that is, the class-level generics, and the syntax format is as follows:

 1 package cn.itcast.day2; 2 Import Java.util.Set; 3 Import Cn.itcast.day1.ReflectField; 4/** 5 * Dao:data Access Object 6 * Data access: CRUD, i.e. additions and deletions 7 * @author aloof Wolf 8 * This class is used to demonstrate how to define a generic class 9 * in this generic class <E> The e represents the actual operation type 10 * After the operation type E is specified, the Crud method defined in the Genericdao class is for the specified type */12 public class Genericdao<e> {private E fi Eld1; Define member variables of a generic type. Public <E> void Add (E x) {}16 public <E> e findbyid (int id) {C-return Nu ll;18}19 public void Delete (E obj) {}21 public void Delete (Int. ID) {}23 public void update (E obj) {}25//public static void update (E obj) {} This definition will cause an error, and the static method does not allow the use of generic parameters-public static<e> void Update2 (E obj) {}//Such a definition is possible, at this time the static method for the type and genericdao<e> specified in the type is two different types of the public set<e> findbyconditions (String where) {null;29 return}30 public static void Main (string[] args) {Genericdao<reflectfield > DAO = new genericdao<reflectfield> ();//Specify a generic class hereThe type of operation is ReflectField32 Dao.add (new Reflectfield (1,3)); Reflectfield rf = Dao.findbyid (1); generi cdao<string> dao1=null;35 new Genericdao<string> (); 36}37}

A generic at the class level is a parameterized type variable based on the type information specified when the class name is referenced, for example, in either of the following ways:

Genericdao<string> dao=null;

New Genericdao<string> ();

Attention:

1. When you parameterize a generic type, the instance of the type parameter must be a reference type and cannot be a base type

2. When a variable is declared as generic, it can only be used by instance variables and method calls (and inline types), not by static variables and static methods, because static members are shared by all parameterized classes, so static members should not have class-level type parameters.

Ix. obtaining the actual type parameters of generics by reflection
 1 package cn.itcast.day2; 2 Import Java.lang.reflect.Method; 3 Import Java.lang.reflect.ParameterizedType; 4 Import Java.lang.reflect.Type; 5 Import Java.util.Date; 6 Import Java.util.Vector; 7/** 8 * This class is used to demonstrate how to get the actual type parameter of the generic by reflection 9 * The source code in hibernate is written in this way. * @author aloof Wolf one * */13 public class USEREFLECTGETG Enericparameter {+ public static void main (string[] args) throws Exception {15/**16 * in the bytecode obtained in this way There is no way to get the actual type parameters of the generic class, 17 * Because the actual parameters of this generic class have been removed from the vector<date> v = new vector<date> when compiling the generic class ( ); * V.getclass (); */21 Method Applymethod = UseReflectGetGenericParameter.class.getMethod ( "Applyvector", vector.class); 23//Gets an array of parameterized types for the generic type, which is the parent class of class type[] types = apply          Method.getgenericparametertypes ();/**26 * Parameterizedtype This class is a parameterized type class, and the types array is stored in a parameterized type parameter, 27 * Take out the first array element and cast it to Parameterizedtype type */29 ParametErizedtype PType = (parameterizedtype) types[0];30 System.out.println (Ptype.getrawtype ()/* Gets the original type, the result of the output is: class Java . util.     vector*/) System.out.println (ptype.getactualtypearguments () [0]/* gets the actual type parameter of the generic, the result of the output is: Class java.util.date*/); 32      }33/**34 * Use reflection to get the type of the parameter list of this method 35 * Through this variable v there is no way to know the type that defines it 36 * But when the variable is given a method as a parameter or return value to use, 37 * Method class provides a series of methods to obtain the parameter list of the method 38 * and is in the form of generics to get the parameter list of the V40 * @param */41 public static void Applyvecto   R (Vector<date> v) {42}43}

Tokens in Java generics mean:

E -Element (used in the collection because the element is stored in the collection)

T -type (Java Class)

K -Key (key)

V -value (values)

N -Number (numeric type)

? -Represents an indeterminate Java type

S, U, V -2nd, 3rd, 4th types

What is the difference between an object and the Java type that these tokens represent?
object is the root class of all classes, objects of any class can be set to this object reference variable, when used may require type casting, but with the use of generic T, E and other identifiers, before the actual use of the type has been determined, do not need to cast a type.

Java Fundamentals Strengthening Summary (ii)--generics

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.