[Java full resolution generic interfaces, classes, package type]

table of Contents

  1. Introduction
  2. Why do we need generics?
   3, generic definition format
   3, the generic benefits
  4, when to use generics?
   5, generics erased
   6, generics compensation
  7, generic application
      7.1 [generic class]
     7.2 [generic method]
     7.3 [] generic interface
  8, genericのwildcards:?
  9, defines a generic

1. Introduction

        Generic Java SE is 1.5 new features, nature of the generic type parameter, that is to say the operation of the data type is specified as a parameter. Generic intended to have "class attributes", the representatives of generics in Java. Generics as a safety mechanism to produce.

2 Why do we need generics?

       We know collection (Collection, Map like container) is used to store any object (Object) series of "container class or interface" Note that "arbitrary objects", meaning we can store these in a class or interface any type of object, but these objects before storage needs unified upcast Object type (because the Object class is so kind of parent class), such as class ArrayList belong to "collections", we can use this class to store arbitrary Object:

Copy the code
the bean Package; 

Import of java.util.ArrayList; 

public class ArrayListDemo { 
    public static void main (String [] args) { 
        
        // First we create a ArrayList object 
        ArrayList Al = new new ArrayList (); 
        
        // to "container" additive element: we added the string "ha ha," the number 2, boolean type true, and finally we even add their own. 
        al.add ( "ha"); 
        al.Add (2); 
        al.Add (to true); 
        al.addAll (Al); 
        // Since ArrayList class overrides the toString (), where we can print directly view the results: 
        System .out.println (Al); 
    } 
}
Copy the code

        Finally, the string is printed: [ha, 2, true, ha, 2, true]

      It is worth noting: 2 here but not int Integer, can only exist because ArrayList object, "adding its own" substantial addAll (al) are all elements of al al stored again, just as print display Like, we successfully added the different types of objects: there String, there are Integer, as well as Boolean. Of course, you can add any object you want to add. Because these objects are stored in a "container" will all be in transition when al for Object type, there did not feel such a "container" with them will be very interesting, what things can put inside. However, convenience often pay the appropriate price.

  We will be the types of elements into "containers" of course not let it sleep, we need to remove the use of storage elements. For these "containers", we generally use the Iterator iterator to get each element. (Described herein without iterators, simply understood that the iterator is a tool "container" in the element taken on the line).

        Suppose the element "container" al Now we need to create in our above operation: string length of the printing vessel, i.e., "ha" in length.

Copy the code
Package the bean. 1; 
 2 
 . 3 Import of java.util.ArrayList; 
 . 4 Import the java.util.Iterator; 
 . 5 
 . 6 {public class ArrayListDemo 
 . 7 public static void main (String [] args) { 
 . 8 // First we create a ArrayList object, and Add Object 
 . 9 the ArrayList new new Al = the ArrayList (); 
10 al.Add ( "ha"); 
. 11 al.Add (2); 
12 is al.Add (to true); 
13 is          
14 // iterator iterators to traverse, and prints vessel string length: 
15 // NOTE: Next () method of the container is stored order, one by one taken first to the last object. 
Al.iterator the Iterator I = 16 (); 
. 17 the while (i.hasNext ()) { 
18 is S = String (String) i.next ();  
. 19 System.out.println (s.length ());
20 is} 
21 is} 
22 is     
23 }
Copy the code

       This is the result:

        Let code analysis: while loop, the first () method of taking out i.next first element "ha", and then installed for the String type (because the time is stored into the Object type, used to use downcast ), so the next print "ha" length = 2. Subsequently loop: Remove the second element iterator: 2, but this is not mandatory type Integer String installed for the type, it throws an exception: a ClassCastException: Conversion exception type.

         This is "able to keep things" brought the price: We use the "container" when storing object and call it change a security risk "type conversion exception", but it needs to know in order to run, unable to find a compile-time . So how do we solve this problem? We found that the problem is "abnormal type conversion," so long as we ensure that the "container" is stored in the same type of element will not appear on this anomaly. Is similarly defined as an array: The int [] array it means designed to store data of type int, String [] array is used to store data of type String. As long as we will on a "container" standard corresponding type of label on it. See here, you should have understood the origin of generics, which is the generic design: the introduction of the concept of type parameters, that object type declaration.

 3, the generic format definition

       Format: class name <type name>, such as:

  

Copy the code
Package the bean. 1; 
 2 
 . 3 Import of java.util.ArrayList; 
 . 4 Import the java.util.Iterator; 
 . 5 
 . 6 {public class ArrayListDemo 
 . 7 public static void main (String [] args) { 
 . 8 // First we create a ArrayList object, and affirmed generic type is String type: String object storage type only 
 . 9 the ArrayList <String> Al = new new the ArrayList <String> (); 
10 al.Add ( "ha"); 
. 11 al.Add ( "asdafa"); 
al.Add 12 is ( "tobeyourself"); 
13 is          
14 // iterator iterators to traverse, and prints the vessel length of the string: here also uses generic iterator 
15 iterator <string> i = al.iterator () ; 
16 the while (i.hasNext ()) { 
. 17 S = String (String) i.next (); 
18 is System.out.println (S + "length =" + s.length ());
19         }
20     } 
21 is      
22 is}
Copy the code

       Operating results as follows:

 3, generic benefits

        In addition to safety problems to solve the above problems thrown i.e., generic class or interface when the object is removed no further downcasting, because when the type is stored.

       In addition, the use of generic safety issues to make an error at compile time rather than run after throwing an exception, it is easy to find programmers timely and accurate problem.

4, when the use of generics?

    General class or interface with <E> in the definition of the identification document in the api, when in use need to use generic mechanism. As ArrayList <E>, Iterator <E>.

 5, generics erased

        Generics is the use of technology at compile time: the compiler to compile the elements in the container when in accordance with <type name> type checking, they do not match, they fail to compile. If all checks are successful, then the compiler, but, .class files generated by the compiler and no <type name> that identifies that the class file is not generic, this is the generic erased.

         Sentence summary is this: when .java files using generics, the compiler automatically erased after the generic identity documents compiled by.

         Due to the generics erased, there is no generic mechanism for class file, but did not use downcast, so why no abnormal running?

 6, generic compensation

          After erasing generics compiler will automatically convert type "generic" definition of the original, so you do not have to do a downcast.

         Erasure and compensation mechanisms for these two generics are inside the compiler automatically, you can understand the principle.

7, Generic applications

  [7.1] generic class

          The so-called generic class is a generic class to use technology, such as the above mentioned ArrayList <E>, Iterator <E> are all java generics classes are defined in Java has a good generic class used directly on it. But sometimes we encounter such a problem:

          Suppose we now have two custom classes: Worker Class and Student class, now we need to get a tool like Tool Student Worker objects and objects, and can operate on objects.

    analysis:

          We might think of the Worker and Tool Student class as class member variables, in order to achieve the operation of these two classes. But there is such a problem, that is, if it's not two classes but a lot of class, and even that numerous categories, namely Tool can operate like any class, call this method to achieve the object by adding a member variable is clearly not feasible. Note that this "add any object", is not this the above said ArrrayList <E> with the characteristics of these classes do? Generic class is to solve the "add any object" arising, ArrayList <E> mentioned here belong to the defined generic classes (Java comes with), here we have to use Tool class to "store any object." so we want Tool class is defined as a generic class, generic class that is custom designed according to your own needs:

First, let's look at a simple definition: Worker Class and Student categories:

Worker categories:

 

Copy the code
 1 package bean;
 2 
 3 public class Worker {
 4     private String name;
 5     private int age;
 6     Worker(){
 7         
 8     }
 9     Worker(String name,int age){
10         this.name = name;
11         this.age = age;
12     }
13     public String getName() {
14         return name;
15     }
16     public void setName(String name) {
17         this.name = name;
18     }
19     public int getAge() {
20         return age;
21     }
22     public void setAge(int age) {
23         this.age = age;
24     }
25     
26 }
Copy the code

 

Student categories:

Copy the code
 1 package bean;
 2 
 3 public class Student {
 4     private String name;
 5     private String sex;
 6     Student(){
 7         
 8     }
 9     Student(String name,String sex){
10         this.name = name;
11         this.sex = sex;
12     }
13     public String getName() {
14         return name;
15     }
16     public void setName(String name) {
17         this.name = name;
18     }
19     public String getSex() {
20         return sex;
21     }
22     public void setSex(String sex) {
23         this.sex = sex;
24     }
25     
26 }
Copy the code

Now we need to Tool class is defined as a generic class :( note format)

Copy the code
 1 package bean;
 2 
 3 public class Tool<E> {
 4     private E e;
 5     
 6     public Tool(E e1){
 7         this.e = e1;
 8     }
 9 
10     public E getE() {
11         return e;
12     }
13     public void setE(E e) {
14         this.e = e;
15     }
16     
17 }
Copy the code

        Here we write is very simple, but the demand has been met, with emphasis on writing a generic class: Tool <E>, where the letter E can write your own favorite code, which is the type of application parameters, the equivalent of a E type parameter represents the Tool <E> can pass any object, let's take a look at the effect of specific use:

Copy the code
Package the bean. 1; 
 2 
 . 3 Tooltest {class 
 . 4 public static void main (String [] args) { 
 . 5 // Suppose there are two objects: a student, a worker 
 6 Student t1 = new Student ( "San", "M" ); 
 . 7 the Worker new new W1 = the Worker ( "John Doe", 20); 
 . 8          
 . 9 // now we use the class to invoke Tool t1 and W1 
10 Tool <Student> Tool new new TS = <Student> (t1); 
. 11 Tool < the Worker> TW = new new Tool <the Worker> (W1); 
12 is          
13 is the effect // Print View 
"data calls using ts t1 in:" 14 System.out.println (+ ts.getE ( ) getName () + ":. "+ ts.getE () getSex ());. 
15 System.out.println (" use of w1 tw data call: ". + tw.getE () getName () +": "+ tw.getE () .getAge ());
16     }
17 }
Copy the code

Print results:

Use ts call data t1 in: Joe Smith: Male
using tw call data w1 in: John Doe: 20

 [7.2] generic method

        The method is similar to the generic class of static design, a general method is passed a fixed parameter type, parameter types, such as public void show (int i) {} is fixed to this method int, but can pass the specified generic method Parameter Type. Generally generic definition of two forms:

        1) Use of generic class parameter type is defined (used):

         The generic class Tool <QQ>, which is the generic parameters QQ. Generic methods can then be written: public void show (QQ qq) {}.

         2) using a custom parameter types are defined:

         If we need to custom parameter types, then we have the generic parameter on the method can be used (positioned before Return Value Type): public <AA> void show (AA aa) {}.

         NOTE: static methods can not access the generic class, if desired generic, we can use the method 2), can be used in a generic method: public static <AA> void show (AA aa) {}

 [7.3] generic interface

        And like the above reason, when we are unsure of the type of object, the use of generics can solve the problem, the use of generic interface and generic class is the same as the same.

       We only need to pay attention, there are two situations when implementing the generic interface: It is assumed that there are generic interface interf <AA>, its implementation class is Tool.

       1) determining the parameter type generic interface implemented:

        Suppose Tool required class parameter of type String, it can be directly written to achieve: class Tool implements interf <String> {} to.

       2) generic interface type parameters of uncertain implementation:

       This time we need to implement generic class classTool <BB> implements interf <BB> {}.

8, through the 泛型 Hythe:?

        We're not sure when the incoming object type we can use? Instead. "?" That generics wildcards.

9, defines a generic

        We know that the use of generic classes: If the clear parameter type, then it represents a generic type; If you use wildcards? , Then the generics on behalf of any kind. But sometimes we want to specify a certain type (not one, but not all) can be used as the parameter type, this should be how to do it?

        Limit the use of generics in Java to solve this problem, namely generic limit. We only need to press this written in the format:

       Limit: <? extends E> E is a parameter indicating the type and all of its subclasses.

       Lower limit: <? Super E> E is a parameter indicating the type and all of its superclass (ie parent).

 https://www.cnblogs.com/fzz9/articles/7674561.html

Author: Wind of

Guess you like

Origin www.cnblogs.com/yhm9/p/11202043.html