1. An element in a generic collection is an inherited relationship
Public classMain { Public Static voidMain (string[] args) {List<Shape> list=NewArraylist<shape>(); List.add (NewCircle ()); List.add (NewRectangle ()); }}classCanva { Public voidDrawall (list<?extendsShape>list) { for(Shape s:list) {S.draw ( This); } }}Abstract classShape { Public Abstract voidDraw (Canva c);}classCircleextendsShape {@Override Public voidDraw (Canva c) {System.out.println ("On canvas" + C + "Draw Circle"); }}classRectangleextendsShape {@Override Public voidDraw (Canva c) {System.out.println ("On canvas" + C + "Draw Rectangle"); }}
2. Generics in a generic class cannot be set to a static member
Generics are actually the errors that occur during the runtime, at compile time, when the runtime actually erases the generic type, static member attribute class members, all objects are shared, and if the generic type is run then the type of the static member in the instance can be different, which violates the syntax of the Java static member
classApple<t>{ Public StaticT color;//generic types cannot be applied to static members PrivateT Info; PublicApple () {} PublicApple (T info) { This. info =info; } PublicT GetInfo () {returninfo; } Public voidsetInfo (T info) { This. info =info; }}
3. When writing a generic class subclass, the inherited generic class must be a primitive class or a generic type-explicit generic class
Cause: If you create a Class C object, the actual JVM will also create an object of the parent Apple class for us, but the missing member type in the Apple class is unknown
class extends Apple<string>{}classextends apple{}classextends apple<t>{ // error }
4. Generic classes are not real classes
A generic class is not a real class, just a type representation of the compile time, which erases a generic type to a native class at run time, such as:list<string> does not exist for this type of class, and does not generate the corresponding class file, the runtime native class List, The resulting class file is List.class, so the use of List<string>.class or instanceof is wrong
Public class Main { publicstaticvoid main (string[] args) { List<string > list=new arraylist<>(); System.out.println (List<string>. class // Error if instanceof // Error } }}
Java-based generic