1. Generic concept
as the name implies, type parameterization (generics)
2. Non-checked type conversions
Assigning a generic type to a primitive type
New Box (); // Rawbox is a raw type of box<t> Box<Integer> intbox = Rawbox; // warning:unchecked Conversion
When you invoke a generic method that refers to a generic type by using a native type reference
New box<>= Stringbox;rawbox.set (8); // warning:unchecked Invocation to set (T)
3. Bounded generic typePrevious:
Public class extends Integer> { private T N; Public Naturalnumber (T N) this . n = n;} Public Boolean IsEven () { return n.intvalue ()% 2 = =0 ; } // ...}
Next session:
Public Static void Super integer> list) {
for (int i = 1; I <=; i++) { list.add (i); }}
4. Multi-generic types
classA {}InterfaceB {}InterfaceC {}//note here that in the A&b&c parameter list, a type must be first, because it is a class typeclassD<textendsA & B & c> {Privated D; PublicD Get () {returnD;}
}classEextendsAImplementsB, C {}voidTest () {NewD<e>(). get ();}5. Generics and inheritance
We have the following code that can be compiled
Newnew Integer (ten= Someinteger; // OK Public void /* * /}somemethod (new Integer); // OKsomemethod (new Double (10.1)); // OK
However, the following code will not compile
Public void /* * /}boxtest (new box<integer> ()); // Errorboxtest (new box<float> ()); // Error
i.e.
The above figure can be obtained:
There is no relationship between box<number> and box<integer>, but they are all subclasses of object.
This is also the case that we often write the following code can not be compiled to reproduce (javac This processing reason please refer to the following type Erase section)
class A {} class B extends a{}
void Test () { ArrayListnew// Error}
But you can use the following logic, which embodies the idea of inheritance in generics:
6. Wildcard and sub-types
This is also a generic way of embodying inheritance:
The last wildcard, sometimes trying to define a method that would allow this method to be called for all the parameter subclasses that satisfy the specified generic type, we can try something like this:
Public Static void extends foo> list) { for (Foo elem:list) { // ... }}
In this way, the following code will be compiled:
InterfaceFoo {}classAImplementsFoo {}classBImplementsFoo {} Public Static voidProcess (LIST<?extendsFoo>list) { for(Foo elem:list) {}}voidTest () {process (NewArraylist<a> ());//OKProcessNewArraylist<b> ());//OK } //The long-lost Nanilist<?extendsFoo> list=NewArraylist<a>();
What's more iffy:
List<?> is the parent type of any list<t>, where T is a concrete type.
Just its usage scenario is when a member method in a specific generic type does not depend on a generic parameter .
7. Capture of a wildcard type
Import java.util.List; Public class wildcarderror { void foo (list<?> i) { i.set (0, i.get (0)); Cannot determine the type, so I.get () The resulting element cannot be saved }}
Need to provide a way to aid in identifying generic parameters, making it possible to compile
Public class wildcardfixed { void foo (list<?> i) { foohelper (i); } // Helper method created so, the wildcard can be captured // through type inference. Private void foohelper (list<t> l) { L.set (0, l.get (0));} }
The following code is not compiled by the
New Arraylist<integer>(); Listextends number> list2 = list; // OKlist2.add (new// compile-time error
8. Type Erase
The following text is quoted from the official Java documentation
type erasuregenerics were introduced to the Java language to provide tighter Type checks at compile time and to Suppor T generic programming. To implement generics, the Java compiler applies type erasure to:replace all type parametersinchGeneric types with their bounds or ObjectifThe type parameters is unbounded. The produced bytecode, therefore, contains only ordinary classes, interfaces, and methods. Insert type castsifnecessary to preserve type safety. Generate Bridge methods to preserve polymorphisminchextended generic types. Type Erasure ensures that noNewClasses is created forparameterized types; Consequently, generics incur no runtime overhead.
Helper methods in generics ensure polymorphism in inheritance
Public classNode {PrivateObject data; PublicNode (Object data) { This. data =data;} Public voidsetData (Object data) {System.out.println ("Node.setdata"); This. data =data; }} Public classMynodeextendsNode { PublicMynode (Integer data) {Super(data);} Public voidsetData (integer data) {System.out.println (integer data); Super. SetData (data); }}//Mynode after being compiled by Javac has the following contentclassMynodeextendsNode {//Bridge Method generated by the compiler// Public voidsetData (Object data) {SetData (Integer) data); } Public voidsetData (Integer data) {System.out.println ("Mynode.setdata"); Super. SetData (data); } // ...}
The specific bytecode content can be obtained by using JAVAP to Decompile mynode.class.
Something about Java paradigm.