Summary of Java Generics

Source: Internet
Author: User

It took about two and a half years from JDK1.4 to JDK5. It took about two years from JDK5 to JDK6 and over four and a half years from JDK6 to JDK7. In JDK5, 6, and 7, only JDK5 was born unexpectedly. A series of new feature significantly changed the daily coding work of Java programmers: Generics, Annotation, Autoboxing, for each statement .... java Generics is a large new feature. compared with C ++ templates, Java Generics has many restrictions and traps, so it is a bit uncomfortable to use, but the more traps there are, the more necessary it is to learn. In the fourth edition of Thinking in java, there are a total of 900 pages apart from the last GUI. The Generics chapter contains more than 90 pages. This blog is mainly the notes of the Generics chapter of Thinking in java.

 

Java Generics can be applied to classes and interfaces, for example:

Public class secure stack <T> {}

Public interface Generator <T> {}

It can also be applied to methods, such:

Public <T> void f (T x ){}

When using generics, remember that, the generic parameter type is not really retained in the runtime generic code (There's no information about generic parameter types available inside generic code .) therefore, List <String> and List <Integer> are the same during running.

 

Note that generics are not always practical, for example:

1: class Manipulator2 <T extends HasF> {
2: private T obj;
3: public Manipulator2 (T x) {obj = x ;}
4: public void manipulate () {obj. f ();}
5 :}
It can be replaced:

1: class Manipulator3 {
2: private HasF obj;
3: public Manipulator3 (HasF x) {obj = x ;}
4: public void manipulate () {obj. f ();}
5 :}
However, if the original code changes a bit, the benefits of generics are shown as follows:

1: class ReturnGenericType <T extends HasF> {
2: private T obj;
3: public ReturnGenericType (T x) {obj = x ;}
4: public T get () {return obj ;}
5 :}
In this example, the get () method returns a specific type T.

 

Some operations are not allowed because the real type is lost in the run time:

1: public class Erased <T> {
2: private final int SIZE = 100;
3: public static void f (Object arg ){
4: if (arg instanceof T) {}// Error
5: T var = new T (); // Error
6: T [] array = new T [SIZE]; // Error
7: T [] array = (T) new Object [SIZE]; // Unchecked warning
8 :}
9 :}
In this case, the Class object parameter can be explicitly passed in, which is called the Type Tag in the book.

1: public class ClassTypeCapture <T> {
2: Class <T> kind;
3: public ClassTypeCapture (Class <T> kind ){
4: this. kind = kind;
5 :}
6:
7: public boolean f (Object arg ){
8: return kind. isInstance (arg );
9 :}
10 :}
Dimension is a Class and HasColor is an Interface, which can be written as follows:

Class ColoredDimension <T extends Dimension & HasColor> {}

Note that there can be multiple after extends, which is different from the inheritance of Class, and the Class should be placed before the Interface

 

Note that Array checks the Data Type strictly:

1: class Fruit {}
2: class Apple extends Fruit {}
3: class Jonathan extends Apple {}
4: class Orange extends Fruit {}
5:
6: public class CovariantArrays {
7: public static void main (String [] args ){
8: Fruit [] fruit = new Apple [10];
9: fruit [0] = new Apple (); // OK
10: fruit [1] = new Jonathan (); // OK
11: // Runtime type is Apple [], not Fruit [] or Orange []:
12: try {
13: // Compiler allows you to add Fruit:
14: fruit [0] = new Fruit (); // ArrayStoreException
15:} catch (Exception e) {System. out. println (e );}
16: try {
17: // Compiler allows you to add Oranges:
18: fruit [0] = new Orange (); // ArrayStoreException
19:} catch (Exception e) {System. out. println (e );}
20 :}
21 :}
Note that Fruit [] fruit = new Apple [10]; if the actual type is Apple, fruit or Orange cannot be added.

 

The Container does not have upcast. Do not confuse the contained elements:

1: public class NonCovariantGenerics {
2: // Compile Error: incompatible types:
3: List <Fruit> flist = new ArrayList <Apple> ();
4 :}
If you want upcast, you can write it like this:

List <? Extends Fruit> flist = new ArrayList <Apple> ();

Note that flist can no longer add new Apple () or new Fruit () or anything, because compiler sees List <? Extends Fruit>, you may think it may be Apple or Orange, and you do not think it is correct to fill in anything.

 

If you want to add to List, you can write as follows:

1: public class SuperTypeWildcards {
2: static void writeTo (List <? Super Apple> apples ){
3: apples. add (new Apple ());
4: apples. add (new Jonathan ());
5: // apples. add (new Fruit (); // Error
6 :}
7 :}
 

 

Code snippet:

 

1: static <T>
2: T wildSubtype (Holder <? Extends T> holder, T arg ){
3: // holder. set (arg); // Error:
4: // set (capture? Extends T) in
5: // Holder <capture? Extends T>
6: // cannot be applied to (T)
7: T t = holder. get ();
8: return t;
9 :}
10: static <T>
11: void wildSupertype (Holder <? Super T> holder, T arg ){
12: holder. set (arg );
13: // T t = holder. get (); // Error:
14: // Incompatible types: found Object, required T
15:
16: // OK, but type information has been lost:
17: Object obj = holder. get ();
18 :}
 

<? Extends T> and <? Super T> among the two, the former is suitable for get to a specific type T, but cannot be set. The latter, on the contrary, can set a specific type, but cannot get to a specific type.

 

Holder, Holder <?> These two classes are different. Holder indicates that it can contain any type. Holder <?> Indicates that a series of the same type can be included, but you do not know which type it is, or even you cannot add an Object to it.


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.