Java Basics-Generics

Source: Internet
Author: User
Tags comparable stub

I. The concept of generics (why generics are needed)?

First, let's look at the following short code:

   Public classGenerictest { Public Static voidMain (string[] args) {List List=NewArrayList (); List.add ("Qqyumidi"); List.add ("Corn"); List.add (100);  for(inti = 0; I < list.size (); i++) {String name= (String) list.get (i);//1System.out.println ("Name:" +name); }    } }

In the coding process as above, we found that there are two main problems:

1. When we put an object into the collection, the collection does not remember the type of the object, and when the object is removed from the collection again, the compilation type of the object is changed to the object type, but its run-time type is still its own type.

2. As a result, it is necessary to//1 the collection element into the specific target type, and the "java.lang.ClassCastException" exception can easily occur.

Two. What is a generic type?

Generic, which is the parameterized type. When referring to a parameter, it is most familiar to define the method when the physical parameter is called and then pass the argument when calling this method. So how do parameterized types understand? As the name implies, the type is parameterized by the original specific type, similar to the variable parameter in the method, when the type is also defined as a Parameter form (which can be called a type parameter), and then the specific type (type argument) is passed in when using/calling.

three. Use of generics

Generics are available in three ways: generic class, generic interface, generic method

3.1 Generic class

The T type represents the type.
K V represents the key value in the keys, respectively.
E represents element.

Attention:
1. Generics can only use reference types, not basic types
2. In a generic class, a generic declaration cannot use a static property | On a static method, it can be declared on a method on a generic method

 Packagecom.zwj.fanxing;/*** Generic class: Use generic * letters when declaring: * T type denotes type.     K V represents the key value in the keys, respectively.  E represents element. Determining type When used Note: 1, generics can only use reference types, cannot base type 2, generic declaration when a letter cannot use static properties | On static methods *@authorAdministrator * *@param<T>*/ Public classStudent<t1,t2> {    PrivateT1 Javascore; PrivateT2 Oraclescore; //static properties cannot be used with generic declarations | On static methods//private static T1 test;             PublicT1 Getjavascore () {returnJavascore; }     Public voidSetjavascore (T1 javascore) { This. Javascore =Javascore; }     PublicT2 Getoraclescore () {returnOraclescore; }     Public voidSetoraclescore (T2 oraclescore) { This. Oraclescore =Oraclescore; }    /**     * @paramargs*/     Public Static voidMain (string[] args) {//Specify type when used (reference type)Student<string,integer> stu =NewStudent<string,integer> (); //1. Security: Type CheckStu.setjavascore ("excellent"); //2, worry: type conversion        intit =stu.getoraclescore ();//Automatic Unpacking    }}
student<t1,t2> generic class: Using generics when declaring

3.2 Generic interface,

 Package com.zwj.fanxing; /**  @author @param */public interface Comparator<t> {    void  compare (T t);    }
The generic letters in the Comparator interface can only be used in methods and cannot be used in global constants
 Packagecom.zwj.fanxing;/*** Generic interface: Same as Inheritance * override method depends on parent class * *@param<T>*/ Public Interface  Packagecom.zwj.fanxing;/*** Generic interface: Same as Inheritance * override method depends on parent class * *@param<T>*/ Public InterfaceComparable<t> {    voidCompare (T t);}//declaring subclasses specifying specific typesclassCompImplementsComparable<integer>{@Override Public voidCompare (Integer t) {//TODO auto-generated Method Stub            }    }//EraseclassComp1Implementscomparable{@Override Public voidCompare (Object t) {//TODO auto-generated Method Stub            }     }//Parent-Class erase, subclass genericclassComp2<t>Implementscomparable{@Override Public voidCompare (Object t) {//TODO auto-generated Method Stub            }     }//Subclass Generic >=-parent genericclassComp3<t>ImplementsComparable<t>{@Override Public voidCompare (T t) {//TODO auto-generated Method Stub            }     }//Parent-class generic, subclass erase error {    voidCompare (T t);}//declaring subclasses specifying specific typesclassCompImplementsComparable<integer>{@Override Public voidCompare (Integer t) {//TODO auto-generated Method Stub            }    }//EraseclassComp1Implementscomparable{@Override Public voidCompare (Object t) {//TODO auto-generated Method Stub            }     }//Parent-Class erase, subclass genericclassComp2<t>Implementscomparable{@Override Public voidCompare (Object t) {//TODO auto-generated Method Stub            }     }//Subclass Generic >=-parent genericclassComp3<t>ImplementsComparable<t>{@Override Public voidCompare (T t) {//TODO auto-generated Method Stub            }     }//Parent-class generic, subclass Erase error
comparable generic interface: with inheritance

3.3 Generic methods

Note: You can only access the information of an object, you cannot modify it

 Packagecom.zwj.fanxing;Importjava.io.Closeable;Importjava.io.IOException;/*** Generic method <> return type front * Only access to object information, cannot modify information *@authorAdministrator **/ Public classTestMethod {/**     * @paramargs*/     Public Static voidMain (string[] args) {Test ("A");//T-->string    }    //Generic Methods     Public Static<T>voidTest (T a) {System.out.println (a); }    //extends <=     Public Static<textendsCloseable>voidTest (T ... a) { for(T temp:a) {Try {                if(NULL!=temp)                {Temp.close (); }            } Catch(IOException e) {e.printstacktrace (); }        }    }}
TestMethod Generic method <> return type front

Java Basics-Generics

Related Article

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.