Abstract: For Java generic tutorials, almost all Java programmers have not only heard of it, but also used it. This article introduces the generic Java tutorial for your learning and reference. Introduction: This article is translated from Java Generics Quick Tutorial. The translation is from the IT comment on Java generic concise Tutorial. The content is as follows: generics are a feature introduced in Java SE 5.0. Since the emergence of this language feature for many years, I believe that almost all Java programmers have not only heard of it, but also used it. Java generic tutorials are free, not free, and there are many. The best teaching materials I have ever met are: The Java Tutorial Java Generics and Collections, by Maurice Naftalin and Philip Wadler valid tive Java (2nd), by Joshua Bloch. despite so many rich materials, I sometimes feel that many programmers still do not quite understand the functions and significance of Java generics. This is why I want to use the simplest form to summarize the basic knowledge of Java generics that programmers need to know. The simplest way to Understand Java generics is to look at it as a convenient syntax, saving you some Java type conversion (casting) operations: list <Apple> box = ...; apple apple = box. get (0); the above Code itself has clearly expressed that box is a List containing Apple objects. The get method returns an Apple object instance, which does not require type conversion. No generics. The code above needs to be written as follows: List box = ...; apple apple = (Apple) box. get (0); obviously, the main benefit of generics is to let the compiler retain the type information of the parameter, perform the type check, and perform the type conversion operation: the compiler ensures that these types of conversions are absolutely correct. Compared with dependent programmers, it is difficult to debug and solve object types and execute type conversion. the compiler can help programmers forcibly perform a large number of type checks during compilation, an error is found. The construction of generics is composed of generics, which leads to the concept of a type variable. According to the Java language specification, a type variable is an unlimited identifier, produced in the following situations: generic class declaration generic interface declaration generic method declaration generic constructor) declare generic classes and interfaces. If one or more types of variables exist on a class or interface, it is generic. Type variables are defined by Angle brackets and placed behind the class or interface Name: public interface List <T> extends Collection <T> {...} simply put, the role played by a type variable is like a parameter, which provides information to the compiler for Type checks. Many classes in the Java class library, such as the generic modification of the entire Collection framework. For example, the List interface we used in the first code above is a generic class. In that code, box is a List <Apple> object, which is an instance of class implementation with a List interface with an Apple type variable. The compiler uses this type variable parameter to automatically convert the type when the get method is called and an Apple object is returned. In fact, this new generic mark, or the get method in this List interface, is like this: T get (int index ); the get method actually returns an object of type T, and T is a type variable in the List <T> declaration. Generic methods are very similar to Constructor. They can also be generic if one or more types of variables are declared on the method and Constructor. The public static <t> T getFirst (List <T> list) method accepts a List <T> type parameter and returns a T-type object. In this example, you can use both the generic classes provided by the Java class library and your own generic classes. Type-safe data writing... The following code is an example. We created a List <String> instance and loaded some data: List <String> str = new ArrayList <String> (); str. add ("Hello"); str. add ("World. "); if we try to mount another object in List <String>, the compiler will prompt an error: str. add (1); // The compilation type cannot be safely read data... When we use the List <String> object, it always ensures that we get a String object: String myString = str. get (0); traverses many classes in the class library, such as Iterator <T>. The functions are enhanced and become generic. The iterator () method in the List <T> interface now returns Iterator <T>, and the object returned by its T next () method does not need to be converted to a type, you can directly obtain the correct type. For (Iterator <String> iter = str. iterator (); iter. hasNext ();) {String s = iter. next (); System. out. print (s);} using the foreach "for each" syntax also benefits from generics. The preceding code can be written as follows: for (String s: str) {System. out. print (s);}, which is easy to read and maintain. The Autoboxing and Autounboxing features are automatically used when Java generics are used, just like the following code: list <Integer> ints = new ArrayList <Integer> (); ints. add (0); ints. add (1); int sum = 0; for (int I: ints) {sum + = I ;}however, you need to understand that, encapsulation and unblocking will lead to performance loss. All should be used with caution. In Java, the child type level can be designed to be the same as that in other languages with object-oriented types: in Java, the child type of type T can be either an extension of type T or a direct or non-direct implementation of type T (if T is an interface ). Because "Become A child type of A certain type" is A transfer relationship, if type A is A child type of B and B is A child type of C, then A is also A child type of C. In the figure above: FujiApple (Fuji Apple) is Apple's child type, Apple is Fruit (Fruit), FujiApple (Fuji Apple) is Fruit (Fruit) all Java types are Object-type child types. Any sub-type A of type B can be assigned a declaration of type B: Apple A = ...; fruit f = a; subtype of the generic type. If an Apple object instance can be assigned a declaration of a Fruit object, as shown above, what is the relationship between List <Apple> and a List <Fruit>? More general. If type A is A child type of type B, what is the relationship between C <A> and C <B>? The answer is unexpected: It doesn't matter. In more general terms, generic types have no relationship with whether they are child types. This means that the following code is invalid: List <Apple> apples = ...; list <Fruit> fruits = apples; List <Apple> apples; List <Fruit> fruits = ...; apples = fruits; why? Why can't an apple be a fruit? In some cases, this can be true, but not in the status and operation of type (class) encapsulation. What happens if I treat a box of apples as a box of fruit? List <Apple> apples = ...; list <Fruit> fruits = apples; fruits. add (new Strawberry (); if so, we can mount different fruit types in the list, which is absolutely not allowed. Another method will give you a more intuitive understanding: a box of fruit is not a box of apples, because it may be a box of another fruit, such as a strawberry (Child type ). Is this a concern? It should not be a big problem. The biggest surprising reason for programmers is the inconsistent usage of arrays and generic types. For generic types, there is no relationship between them and their subtypes. Arrays are related to child types. If type A is A child type of type B, A [] is A child type of B: 1 Apple [] apples = ...; 2 Fruit [] fruits = apples; but wait a moment! If we put the problem exposed in the previous discussion here, we can still add the strawberrie (Strawberry) object to an apple array: apple [] apples = new Apple [1]; Fruit [] fruits = apples; fruits [0] = new Strawberry (); this way, you can compile the photo, however, an ArrayStoreException is thrown during running. In terms of data storage operations, Java runtime needs to check the compatibility of data types. This kind of check obviously brings some performance problems. You need to understand this. Again, generics are safer to use and can "correct" the defects in this type in the Java array. Now you may be wondering why there is a relationship between this type and the child type on the array. I will give you the answer in the book Java Generics and Collections: if they are irrelevant, you cannot pass an array of unknown objects into a method (instead of encapsulating them into Object [] Every time), just like the following: void sort (Object [] o); after the appearance of generics, this array personality is no longer necessary for use (we will talk about this in the following part ), it should be avoided. In the previous sections of this article, wildcards have already said that subtypes of generic types are not correlated. However, sometimes we want to use generic types as normal: shape the reference of a generic object. For example, suppose we have many boxes, each box contains different fruits. We need to find a way to process any box of fruits in a universal manner. In more general terms, A is A sub-type of B. We need to find A way to assign a c <A> type instance to a c <B> type declaration. To do this, we need to use the extension declaration with wildcards, as in the following example: List <Apple> apples = new ArrayList <Apple> (); List <? Extends Fruit> fruits = apples; "? Extends is a subtype correlation of generic types. It becomes a reality: Apple is a child type of Fruit, and List <Apple> is List <? Child type of extends Fruit>. Now I will introduce another wildcard character :? Super. If type B is A super type (parent type) of type A, C <B> is C <? Sub-type of super A>: List <Fruit> fruits = new ArrayList <Fruit> (); List <? Super Apple> = fruits; why does it work with wildcard characters? The principle is already quite clear: how can we use this new syntax structure?? Extends: Let's take a look at the example used in the second part. Here we talk about the subtype relevance of Java Arrays: Apple [] apples = new Apple [1]; Fruit [] fruits = apples; fruits [0] = new Strawberry (); as we can see, when you add a Strawberry object to an Apple object array declared as a Fruit array, the code can be compiled, however, an exception is thrown during running. Now we can use wildcards to convert related code into generics: because Apple is a subclass of Fruit, we use? Extends wildcard, so that you can assign a List <Apple> object definition to a List <? On the declaration of extends Fruit>: List <Apple> apples = new ArrayList <Apple> (); List <? Extends Fruit> fruits = apples; fruits. add (new Strawberry (); this time, the Code cannot be compiled! The Java compiler will prevent you from adding strawberry to a Fruit list. During compilation, we can detect errors. during runtime, we do not need to check to ensure that incompatible types are added to the list. Even if you add a Fruit object to the list, it won't work: fruits. add (new Fruit (); you can't do this. In fact, you cannot use one? Write any value in the data structure of extends. The reason is very simple. You can think like this? The extends T wildcard tells the compiler that we are processing the child type of A type T, but we do not know what the child type is. We are not allowed to add any data of this type to ensure data type security. On the other hand, we know that no matter what type it is, it is always a child type of type T. When we read data, we can ensure that the data obtained is a T-type instance: fruit get = fruits. get (0 );? Super usage? What is super wildcard? Let's take a look at this: List <Fruit> fruits = new ArrayList <Fruit> (); List <? Super Apple> = fruits; we can see that fruits points to a List containing a supertype of Apple. Similarly, we do not know what superclasses are, but we know that Apple and any Apple subclass are compatible with their types. Since this unknown type is Apple and it is also the superclass of GreenApple, we can write: fruits. add (new Apple (); fruits. add (new GreenApple (); if we want to add Apple's superclass to it, the compiler will warn you: fruits. add (new Fruit (); fruits. add (new Object (); because we don't know what kind of superclass it is, all such instances are not allowed to join. What if I get data from this type? The result shows that you can only retrieve the Object instance: because we don't know what the superclass is, the only thing the compiler can ensure is that it is an Object, because the Object is a superclass of any Java type. What are the access principles and PECS rules? Extends and? If you want to obtain data from a data type, use? Extends wildcard if you want to write an object into a data structure, use? If you want to save and retrieve the super wildcard, do not use the wildcard. This is the access principle that Maurice Naftalin mentioned in his book "Java Generics and Collections" and the PECS law that Joshua Bloch mentioned in his book "valid Java. Bloch warned that this PECS refers to "Producer Extends, Consumer Super", which is easier to remember and use.