Getting Started with generics basics for Java

Source: Internet
Author: User

1. The role of generics

Prevent arbitrary placement of any object, using generics can only be added by the type that we specify when we use it and compile-time check accordingly, after compiling the check will be stripped of the corresponding generic information (the runtime does not have this information), the type conversion will be automatically converted to the corresponding information

 Public classGenenricyDemo1 { Public  Static<T>t test1 (T t) {returnT; }         Public<T>t Test2 (T t) {returnT; }         Public Static voidMain (string[] args) {String test1= Genenricydemo1.test1 ("a"); String test2=NewGenenricyDemo1 (). Test2 ("b"); }    }

2. Generic compile-time type checking (generics are not polymorphic.) Direct comparison of class files into classes, but can be polymorphic in arrays)

 Public classGenericyDemo2 { Public Static voidMain (string[] args) {//arraylist<object> ArrayList = new arraylist<string> ();//compile-time errorArraylist<string> ArrayList =NewArraylist<> ();//compile-time normalArrayList ArrayList1 =NewArraylist<string> ();//compile-time normalArraylist<object> Arraylist2=arraylist1;//compile-time, compile-time line-by-line check//arraylist2=arraylist;//Compile-time error
Vector<string > [] vct=new vector<string >[10]; Compile error, parameterized type does not have an array representation
arraylist<int> str=null;//compilation errors, generic parameters can only be used on objects that cannot be basic types of data and are not automatically wrapped
  Object [] objs= new String [ten]; Compile-time through
  Interface genericydemo9iface<genericydemo> {//? extends Genericydemo9fater is not available (class interface, etc.)
}}

3. Inheritance Implementation generics

@SuppressWarnings (" All") Public classGenericydemo3<b, A, c> extends genericydemo3father<a> implements Genericydemo3iface<b> {    Private StaticFinal String Parameterizedtype =NULL; Privatec C; @Override PublicString Test (B t) {returnt.tostring (); }    Private<T>t Test3 (T t) {returnT; }     Public Static voidMain (string[] args) {type[] genericinterfaces= GenericyDemo3.class. Getgenericinterfaces (); System. out. println (genericinterfaces[0]); Type Superclass= GenericyDemo3.class. Getgenericsuperclass (); if(Superclass instanceof Parameterizedtype) {type[] actualtypearguments=((parameterizedtype) superclass). Getactualtypearguments (); System. out. println (actualtypearguments[0]); } GenericyDemo3 GenericyDemo3=NewGenericyDemo3 (); Try{method[] methods=Genericydemo3.getclass (). Getdeclaredmethods ();  for(Method method:methods) {if(Method.getname (). Equals ("test3") {method.setaccessible (true); Object Invoke= Method.invoke (GenericyDemo3,"String"); if(Invoke.getclass () = = String.class) {System. out. println (Invoke);//has output string//because the bytecode files we get are still themselves                    }                }            }        } Catch(Exception e) {e.printstacktrace (); }    }}InterfaceGenericydemo3iface<t> {     PublicString Test (T T);}classGenericydemo3father<t> {     PublicString test1 (T t) {returnt.tostring (); }}

4. The difference between non-writing and writing obejct of generics

 Public classGenericyDemo4 {//do not write generic defaults to object, compile without type checking//write generic to object, compile without type checking     Public Static voidMain (string[] args) {ArrayList ArrayList=NewArrayList (); Arraylist.add ("a"); Arraylist.add (1); ArrayList<Object> arraylist1=NewArraylist<>(); Arraylist1.add ("a"); Arraylist1.add (1); }}

5. Get the type of the generic type

 Public classGenericyDemo5 { Public Static voidMain (string[] args) throws Exception {method[] methods= Genericydemo5test.class. GetMethods ();  for(Method method:methods) {if(Method.getname (). Equals ("Test") ) {type[] parametertypes=method.getgenericparametertypes (); System. out. println (parametertypes[0]); }        }    }}classGenericydemo5test { PublicVector<string> Test (vector<string>Str) {        return NULL; }}

6. Erasing a generic type

 Public class GenericyDemo6 {   publicstaticvoid  main (string[] args) {      ArrayList  New arraylist<>();      ArrayListNew arraylist<>();      System. out. println (Arraylist.getclass () ==arraylist1.getclass ()); // true }}

7. Characteristics of wildcard characters:

1) can be used to declare the type and declare the method on the parameters, the instantiation must be specified, can not be used to declare the parameters of the class;

2) can only input and output, can not be modified;

3)? Extends upper limit (inheritance or realization relationship);

4)? Super lower limit (inheritance or implementation of the relationship, can be a lower or lower limit of the sub-Class);

 Public class GenericyDemo7 {    publicstaticvoid  main (string[] args) {         ArrayListNew arraylist<>();        Arraylist1.add (new arraylist<>());//Cannot add new Object (); The reason is explained earlier     }}

 Public classGenericyDemo7 { Public Static voidMain (string[] args) {ArrayList<? Extends genericydemo7iface> List1 =NewArraylist<>(); ArrayList<GenericyDemo7Son> List2 =NewArraylist<>(); List2.add (NewGenericydemo7son ()); List1=List2; System. out. println (List1.Get(0)); //List1.add (New Genericydemo7son ());//compilation errors, only null values can be added    }}classGenericydemo7son implements Genericydemo7iface {}InterfaceGenericydemo7iface {}

Getting Started with generics basics for Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.