Generics and wildcard characters for Java

Source: Internet
Author: User
Tags addall

Generic type:
1. Generic class
Class a<t>{
}
2. When creating an instance, you need to assign a value to its type variable

3. Generic methods
Class a<t>{
Public T fun1 () {}
public void fun2 (t T) {}
None of the above two are generic methods, they are a method inside a generic class
Discovery method requirements need to have generic definitions on methods
Public <T> T Fun3 () {}//this is a generic method
}

Class b{
Public <T> fun1 () {}//are also generic methods, and generic methods do not necessarily need to be in a generic class
}
* Generic methods and generic classes do not have a direct relationship,

4. Use of generic classes
* Generics defined in the generic class
> can be used in the return value of a method
> can be used in the parameters of the method
> can be used in local variables
Class c<t>{
Public T fun1 () {
T t = ...//yes
New T ()//can not, will error
}
public void fun2 (t T) {}
}
Simple to remember: generics can be used on the left and not on the Right.

5. Inheritance and implementation of generics
* Subclasses are not generic classes: you need to pass a specific type constant to the parent class
> All generic parameters in the parent class will be replaced by this type constant
* Subclasses are generic classes: you can pass a specific type parameter to the parent class, and also pass a generic parameter
Class AA1 extends a<string>{}
Class Aa2<e> extends a<e>{}


=========================================
=========================================
=========================================

wildcard character of generic type

1. Scenarios used by wildcard characters

The formal parameters of the method!

2. Advantages of wildcard characters
Make the method more general!

3. Wildcard classification
Unbounded Pass with:?
Sub-Class qualification:? Extends Object
Parent class qualification:? Super Integer

4. Wildcard Disadvantage
Make variable use no longer convenient
Unbounded: parameters and return values are generic methods and cannot be used!
Subclass: a method with a generic parameter cannot be used
Parent Class: A method that returns a generic value cannot be used

5. Compare wildcard characters
Boolean AddAll (collection<e> C)

list<number> numlist = new Arraylist<number> ();
list<integer> intlist = new Arraylist<integer> ();
Numlist.addall (intlist);//addall (collection<number> c), passing list<integer> error


Boolean AddAll (collection<? extends e> c)

list<number> numlist = new Arraylist<number> ();
list<integer> intlist = new Arraylist<integer> ();
Numlist.addall (intlist);//addall (collection< extends number> c), passing list<integer>

Code Demo

1  packagegenericity;2 3  public classDemo1 {4 5    classA<t>{6        PrivateT t;7         publicT fun1 () {8            returnt;9        }Ten         one         public voidfun2 (t T) { a             -        } -         the}//is a generic class -     -    classBextendsa<string>{}//B is not a generic class -     +    classC<e>extendsa<integer>{}//is also a generic class -     +    classD<e>extendsa<e>{}//is also a generic class a     at     public voidfun1 () { -D<string> d =NewD<string> ();//the generics in class D and class E are now replaced by String. -    } -}

1  packagegenericity;2 3 Importjava.util.ArrayList;4 Importjava.util.List;5 6 Importorg.junit.Test;7 8  public classDemo2 {9 Ten @Test one      public voidFun1 () {//the Battle of collections and Arrays a         /* - * First time contest - * array: I can create a 10 space for anything that can exist the * collection: I can create a space where everything is free and unlimited -          */ -object[] arr1 =NewObject[10]; -List List1 =NewArrayList (); +          -         /* + * Second Contest a * array: I can create a 10 space that only holds a string type at * Collection: I couldn't do it before, but now I can, I can create an infinite space that only holds a string type.  -          */ -string[] arr2 =NewString[10]; -List<string> List2 =NewArraylist<string>(); -          -         /* in * Third Contest - * array: I can use object[] to exist string[], but arr3[0] = new Integer (100);//programming no error, run report: arraystoreexception to * collection: because of generic erase, directly do not give me compile via list<object> list3 = new arraylist<string> () +          */ -object[] ARR3 =NewString[10]; thearr3[0] =NewInteger (100);//programming without error, run Report: arraystoreexception *          $ //list<object> list3 = new arraylist<string> ();Panax Notoginseng           /** - * The above code is an error, because generics are only known to the compiler, and the JVM does not recognize generics at all, generics the * Run-time erase, If the above code does not error, and run-time generic will be erased, then the following jokes appear + * List.add (new Integer (100)), Then the array is a good joke set, you can put everything, a * What's the limit, joke?  the            *  + * Then we zoom in on the problem of a way to print the data in the collection, -            */ $     } $      -      public voidfun2 () { -List<integer> intlist =NewArraylist<integer>(); the          -List<string> strlist =NewArraylist<string>();Wuyi //print1 (intlist);//Direct error, The reason and the same as above, because there is an argument to the parameter assignment process, the compiler directly does not let through the list<object> list= intlist=new arraylist<integer> (); the         //think: every different type of collection requires a different way of printing, and That's too much, so there 's a Wildcard. -          wu         //This makes it possible to use a common printing method. - Print2 (intlist); about Print2 (strlist); $     } -      -      public voidPrint1 (list<object>List) { -          a     } +      the     /** - * This is a wildcard. $      * @paramList the      */ the      public voidPrint2 (list<?>List) { the         /* the * Thinking: Although all can be called, but has brought some parameters to use the above restrictions -          */ in //list.add (new Integer);//error, because do not know the delivery in the end is above, if it is a string, that programming through the joke, add () void theObject obj = List.get (0);//the reason why this parameter can be used is because object is the parent class of all classes, and the Get () method is not allowed to expire the          about         /* the * Summary: the * 1, when using wildcards, the generic class of the parameters of the generic method played a side effect, can no longer use!  the * 2, When using wildcard characters, the return value of the generic class is a generic method, also void!  + * The benefits of wildcards: you can make generic types more generic! In particular, the parameter uses wildcard characters when calling a method!  -          */ the     }Bayi      the      public voidfun3 () { theList<integer> intlist =NewArraylist<integer>(); -List<long> longlist =NewArraylist<long>(); - Print3 (intlist); the Print3 (longlist); the     } the      the     /** - * Subclass wildcard, must be a subclass of number and number to pass the parameter the * The disadvantage is that the flexibility of the parameters is reduced, but closing a door opens a door the * Because all the tiredness is a subclass of number, all the return values can be accepted by using #, and the Get () method is liberated, that is, a method that returns a generic type can use the the      * @paramList94      */ the      public voidPrint3 (list<?extendsNumber>List) { theNumber Nu = List.get (0);//correct the //list.add (new Integer);//But the Add () method is still discarded, thinking that I do not know which subclass of the specific incoming, if the incoming is a long, add an integer joke98     } about      -     /**101 * Parent class wildcard, allow only integer pass parameters102 * The disadvantage is that the flexibility of the parameters is reduced, but closing a door opens a door103 * The advantage is that all classes are the parent of an integer, and all methods with a generic parameter can be used104 * But conversely, a method that returns a generic type cannot be used because a subclass cannot receive the value of a parent class the      * @paramList106      */107      public voidPrint4 (list<?SuperInteger>List) {108List.add (NewInteger (100));//correct109         /* the * But a method with a return value of generic cannot be used111          */ the //Integer nu = list.get (0);//Error113     } the      the      the}

Generics and wildcard characters for Java

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.