Generics introduce the limitations of generics traditionally written:
In Java, generic classes and methods can only use specific types, either basic data types or custom types. If you want to write code that can be applied to more than one type, this stereotype will be a lot of restraint!
There are three ways to address this limitation:
1. Polymorphic: Sets the parameter type of the method to the base class, then the method can receive any class exported from this base class as a parameter.
class // defining a base class class Test () { publicvoid F (Primary p) {...}}
2. The parameters of the method use interfaces: any class that implements the interface can satisfy the method.
Interface // Defining Interfaces class Test () { publicvoid/// All classes that implement the interface can be parameters {...}}
3. Use generics.
Description of generics:
Generics Implement the concept of parameterized types so that code can be applied to some kind of non-specific class, rather than to a specific class or interface.
Simply put, the code can be applied to a wide variety of types.
Translation of generic expressions (last See):
1. When a program invokes a generic method, the compiler inserts a type conversion if the generic return type is erased.
Pair<employee> buddies == Buddies.getfirst ();
? After erasing the return type of GetFirst, the type of object is returned, and the compiler automatically inserts the forced type conversion of the employee.
? In other words, compile it to translate this method call into two virtual instructions:
◇ call to the original method Pair.getfirest.
◇ cast the returned object type to the employee type.
2. A forced type conversion is also inserted when accessing a generic field.
It is assumed that the first and second domains of the Pair class are public (this is not a good programming style, but it is legal in Java syntax).
Expression: Employee buddy = Buddies.first; Forced type conversions are also inserted into the result bytecode;
Simple generics:
use generic predefined parameter types:
Description: Basic data type cannot be a type parameter
materializing type parameters when used
Summary
The primary use of generic classes is in the collection, where the code encapsulates a ArrayList, so that when we write the class, we are not constrained to the specific class, because the type used is specified when the object is initialized .
Why are we doing this? If this implementation class is not generic, if you are dealing with multiple types of data, you will write multiple implementation classes to handle.
Tuples: Simple tuple instances:
Implementing a longer tuple by inheritance mechanism
Generic interface Description:
Generics can also be applied to interfaces, and class and interface type parameters should be consistent, either t or other.
One of the most common uses of generic interfaces is to implement the Iterable interface to implement an iterative approach!
Instance:
Importjava.util.ArrayList;Importjava.util.Date;ImportJava.util.Iterator;ImportJava.util.Random; Public classRandomlist<t>ImplementsIterable<t> { Privatearraylist<t> storage =NewArraylist<t>(); PrivateRandom Rand =NewRandom (NewDate (). GetTime ()); Public voidAdd (T Item) {Storage.add (item); } PublicT Select () {returnStorage.get (Rand.nextint (Storage.size ())); } /*implementing the Iterable interface*/ PublicIterator<t>iterator () {returnStorage.iterator (); }}
Generic method Description:
there is no direct relationship between owning a generic method and whether it is a generic class , that is, the generic method can change independently of the Class!
Example:
Type description: An explicit type description:
In a generic method, you can explicitly indicate the type of the parameter, but it is seldom used!
Variable parameter list:
A generic method and a mutable argument list can co-exist well
Qualification description for type variable:
1. Add a qualification to make the type variable have a specific function.
2. You can have multiple qualifiers (interfaces and classes are all possible), but be aware of the order.
Why don't implements the keyword? After all, comparable is an interface:
extends Boundingtype>
This code indicates that T should be a subtype of the binding type (Boundingtype). The T and binding types can be classes, or they can be interfaces.
If T is an interface, then the method call simultaneous come in is the implementation class of T is also possible. Extends is closer to the concept of sub-class, so choose Extends.
Mysterious EraseQuestions:
We would probably think of c1!=c2 as a result of false, because C1 cannot load INTEGER,C2 nor can it be loaded into string.
Description:
inside the generic code, you cannot get any information about the type of the generic parameter, that is, you cannot get the specific type, you can only learn information such as type parameter identifiers and generic boundaries .
Java generics are implemented using erase:
This means that when you use generics, any specific type of information is erased, and the only thing you know is that you are using an object. So the problem is C1==C2, true. Both of these forms are erased as their "native" type, the list.
original type and erase:
the virtual machine does not have a generic type object, and all objects belong to the normal class . Whenever a generic type is defined, a corresponding primitive type is automatically provided, and the process of restoring the generic type to the original type is called erasing .
The name of the original type is the generic type name after the type parameter is deleted. Erase the type variable and replace it with the qualified type (the variable with unqualified type defaults to object).
The original type of the left image becomes: public class Test<object>, and all t becomes object right: public class Test<comparable>, and all t becomes object.
Description
It is not difficult to understand why, with the addition of bounds, we can call Obj.compareto (), because after erasing the type variable, T is reverted to comparable, The effect is that any subclass that implements the comparable can call the Compare () method of the Test object. If generics are present in Java 1.0, then this feature will not be implemented using erase--it will use materialization to keep the type parameters as the first class of entities, so you can perform type-based language operations and reflection operations on the type parameters.
once again, we emphasize:
New
It seems that class test should know that it is now working on cat, and that the generic syntax strongly implies that type T is being replaced everywhere in the class. But that's not the case, and whenever you're writing this class of code, you have to always remind yourself that it's just an object.
The compensation for the erase.
Talk about the border again
1. The boundary allows you to set restrictions on the type parameters used for generics. While this allows you to enforce the types that generics can apply, a more significant potential effect is that you can invoke methods according to your own boundary type.
2. Because the erase removes the type information, the methods that can be called with unbounded generic parameters can only be those that can be called with object, then you use these type bytes to invoke the method.
Wildcard charactersDescription:
1.Java generics are mandatory type detection, and subtypes of generic types are unrelated.
publicclass Test { Public Static voidMain (string[] args)throwsexception{List<Integer> Listinteger =NewArraylist<integer>(); List<String> liststring =NewArraylist<string>(); Printcollection (Listinteger); Printcollection (liststring); } Public Static voidPrintcollection (collection<object>collection) { for(Object obj:collection) {System.out.println (obj); } } } //An Integer string is a subtype of object, but the result is an error, which indicates that generics do not consider inheritance relationshipsThe Method Printcollection (collection<object>) in the type gernerictest isn't applicable for the arguments (Lis t<integer>)
2. We want generics to have some object-oriented features like the normal class:
-
- Transition up to a generic object.
- Down to a generic object.
3. To enable generics to have some object-oriented inheritance, Java introduces some of the concepts of wildcards: unbounded wildcard characters?
to make the subtypes of generics still relevant, you can use the unbounded wildcard character directly:
use the wildcard upper bound "? Extends T" To specify an inheritance relationship
Description
? The fundamental implementation of extends T is the automatic upward transformation of generics.
use the wildcard character Nether "? Super T"
Use the method and explain ibid.
Java: Generic Foundation