1. Experience Generics
Generics are provided to the Javac compiler to limit the input types in the collection, to allow the compiler to block illegal input in the source program, to eliminate "type" information when the compiler compiles a collection of type descriptions, to make the program run inefficiently, and for parameterized generic types, getclass () The method return value is exactly the same as the original type. Because the compiled bytecode removes the generic type information, as long as you can skip the compiler, you can add other types of data to a generic collection, for example, by using reflection to get the collection, call its Add method.
arraylist<string> collection1 = new arraylist<string> ();
arraylist<integer> collection2 = new arraylist<integer> ();
System.out.println (collection1.getclass () = = Collection2.getclass ()); True
Public Static voidMain (string[] args)throwsException {ArrayList<String> Collection1 =NewArraylist<>(); Collection1.add ("ABC"); ArrayList<Integer> Collection2 =NewArraylist<>(); System.out.println (Collection1.getclass ()= = Collection2.getclass ());//trueCollection2.getclass (). GetMethod ("Add", Object.class). Invoke (Collection2, "ABC"); System.out.println (Collection2.get (0));//ABC}
Parameterized types do not consider inheritance relationships for type parameters:
vector<string> v1 = new vector<object> ();//Error! Don't write <Object> Yes
Vector<object> v2 = new vetcor<string> (); Error
When you create an array, the elements of the array cannot use the parameterized type, for example, the following statement is incorrect
vector<integer> vectorlist[] = new vector<integer>[10];
Study questions: Does the code below make an error?
Vector v1 = new vector<string> (); Parameterized type to original class, no error
Vector<object> v2 = v1; The original type to the parameterized type, you can
2. Generic wildcard extension app
In a generic type? Wildcard characters
? represents any Type
Define a method that prints out all the data in a collection of arbitrary parameterized types, how is this method defined?
Public void printcollection (collection<?> cols) { for(Object obj:cols) { System.out.println (obj); } // cols.add ("string") // error, because it does not know that its future match is bound to be string // Yes, this method has no relation to the type parameter cols=New hashset<date> (); //? Can reference other types }
To qualify the upper bounds of a wildcard:
Correct: vector<? Extends number> x = new vector<integer> ();
To limit the bottom bounds of a wildcard:
Correct: vector<? Super integer> x = new vector<number> ();
Qualifying wildcard characters always includes themselves.
Java high-tech-generics