Generic type
I. Defining a generic class
public class Pair<t>
{
Private T _first;
Public Pair (T first) {This._first = first;}
Public T GetFirst () {return _first;}
}
Type variables in Java are used in uppercase and relatively short
E: element type k,v the keyword of the table and the value of type T (u/s) any type
Generic method: Either the return type is generic or the parameter is generic
public static <T> Getmiddle (T ... a)
{
return A[A.LENGTH/2];
}
When called, the program automatically recognizes the generic type. Occasionally there will be errors
C + +: similar to C + + template classes, but with essential differences
Two. Limit a type variable to provide a parent class interface for the type variable, which makes it easier for the type to have some methods (using extends instead of implements)
public static <t extends compareable> t Getmiddle (t ...);
Multiple qualifying classes can be bound, using & separated
T extends Compareable & Serializable
Three. Generic code vs. virtual machines
All generic code will provide an original type. is to remove the generic type name after the type parameter and replace it with the qualified class. No qualifying class is substituted with object. With more than one qualifying class, the first qualified class will be used instead of T and inherit the second qualified class
public class Pair
{
Private Object _first;
Public Pair (object first) {This._first = first;}
public Object GetFirst () {return _first;}
}
Each template instantiation of c++:c++ produces a different type, a phenomenon that becomes "template code bloat"
Four. Type erase and polymorphic call, bridge method
Translation generic expression: If the return type is erased, the object type is returned by default, and the compiler forces the insert type conversion
Translating generic methods: After a generic class parent class type is wiped out, the method of overriding the parent class may have a condition that is corrupt for subclasses
Complete method: public static Datainterval extends pair<data>
After erasing type: public static datainterval extends Pair//all fields or methods of T in this class are replaced by object
If a subclass overrides a method of the parent class: for example: Setsecond, the parent argument list is object, and the parameter list of the subclass is still the data type defined by the subclass, which violates the overridden feature. It destroys polymorphism. Which method does it call?
Parent class: Setsecond (Object value);//setsecond (T value);
Subclass: Setsecond (Data value);
Setsecond (Object value);//Inherited parent class
Call
Datainterval interval = new Datainterval (...);
Pair<data> pair = interval;
Pair.setsecond (AData);
Because pair refers to the Datainterval object, we should use Datainterval.setsecond. But the problem is that type erasure conflicts with polymorphism. I don't know which one to use.
The JVM works as follows:
1. The variable pair is declared as Pair<date> the type has only one Setsecond (object) method, and the virtual machine calls the Setsecond (object) method with the object referenced by the pair.
The object referenced by 2.pair is DateInterval, so the Dateinterval.setsecond (object) method is called, and this method is the bridge method.
3. This bridge method invokes the Dateinterval.setsecond (Date) method.
Workaround: A bridge method needs to be generated within the compiler
public void Setsecond (Object value)
{
Setsecond (Data) value); Coercion type Conversion! The Setsecond (Data value) method is called regardless of how it is called
}
If the Getsecond method of the subclass is overridden, and the bridge method is used
Class DateInterval extends Pair<date> {
Public Date Getsecond () {
Return (Date) Super.getsecond (). Clone ();
}
}
Post-erase type programming:
Data Getsecond ();
Object Getsecond ();//is also a two-way
In fact, the JVM can use the return type to differentiate which method to invoke
The bridge method is not only used for generic types; it is also possible to specify a more stringent return type when one method overrides another, indicating the method to invoke:
Public Employee Clone () throws Cloonenotsupportedexception {... }
In fact, the employee class has two clone methods, Object Clone (), and employee clone; The synthetic bridge method invokes the new defined method
The fact of the Java Generics transformation:
1. There are no generics in the virtual machine, only ordinary classes and methods
2. All type parameters will be converted using a qualified type
3. The bridge method is synthesized to keep polymorphic
4. To maintain type safety, insert forced type conversions if necessary
Five. Limitations of generics
1. Cannot use and type instantiate type parameters for example: no pair<double>, only pair<double> you can use the wrapper wrapper base type
2. Run-time type queries are only available for the original type
Objects in a virtual machine always have a specific non-generic type, and all type queries produce only the original type. (Instanceof,getclass method, etc.). If the use of instanceof or coercion type conversion is involved, a warning will be generated)
pair<string> STROBG = "..."; ==>pair
pair<employee> EMPOBG = "..."; ==> Pair
if (stringobg.getclass () = = Empobg.getclass ())//they is equal
3. You cannot create a parameterized array
pair<string>[] table = new PAIR<STRING>[10]
Pair[] table can be converted to object[] array, if you attempt to deposit other types of variables, you will throw an exception
If you are collecting parameterized type objects, there is only one safe and efficient way to use allaylist
Allaylist<pair<string>>
4.Varargs Warning: If the number of parameter lists is variable, then it will produce something similar to the above, the number of parameter lists is variable in fact, the parameter list of all the same type of parameters wrapped in the array. A warning is generated that can be annotated with @suppresswarnings ("Unchecked") (Javase 7 can also be annotated with @savevarargs)
@Savavarargs
Public static<t> void AddAll (collect<t> coll, T ... ts);
5. Cannot instantiate a type variable, cannot construct a generic array
Cannot be new T (...), new t[] or t.class, because when the type is erased, T becomes the object type
or Object[2],new object () is not what we want to see, you can use reflection to create an object
First. T.class is not legal.
public static <T> pair<t> Makepair (class<t> cl)//<t> indicates a generic method
{
try{
return new Pair<> (Cl.newinstance (), cl.newinstance ())
}
catch (Exception ex)
{
return null
}
}
Pair<string> p = pair.makepair (String.class);
6. Invalid type variable in static context of generic class
Cannot reference a type variable in a static field or method
public class Singleton<t>
{
private static T singleinstance; Error
public static T Getsingleinstance//error
{
if (singleleinstance = = null)
return singleinstance;
}
}
7. Cannot throw or catch instances of generic classes
Throwable that are based on generic class expansion are illegal.
8. Note The conflict after type wipe
Five. Generic inheritance
No matter what the relationship between s,t. Pair<s> and pair<t> do not have any relationship, you can not call the method in the class, resolve see "Six, wildcard"
You can always. The generic type is converted to the original type, which can handle legacy code. But there's still no guarantee of security.
Six. Wildcard type
pair<? Extends employee>
Represents any generic pair type whose type parameter is a subclass of employee, such as Pair<manager>, but not pair<string> and other types
public static void Paintbuddies (<PAIR<? extends employee> P)
Type <Pair<Manager> is <pair<? Extends subset of Employee>
1. Wildcard Descriptor Type limit
2. Unlimited top-Pass wildcard
3. Wildcard Capture
Vi. Reflection and Generics
Class is generic, for example String.class is actually an object of the Class<string> class (in fact, it is the only object)
The type parameter makes the return value of the Class<t> method targeted.
T newinstance ()
T cast (Object obj)
T[] Getenumconstances ()
...
Original book 554 pages
Java Learning Note (Core Java) 8 generics