Java Basics-Generics

Source: Internet
Author: User
Tags gety

Turn http://www.cnblogs.com/1693977889zz/p/7095460.html

First, the definition

Generics (generic) refers to the ability to parameterize types. You can define a class or method with a generic type, and then the compiler replaces it with a specific type (generic instantiation).

The primary advantage of using generics is the ability to detect errors at compile time, rather than at run-time.

It is a feature that appears after jdk1.5 to enhance security. My understanding is that it is more like a special specification, such as when the programmer in the call, or the client in the introduction of the time, always can not be a mixed bag, how to do?! The previous definition says input a string type, this side does not obey, does not need to let you carry on, directly lets you hang off.

Ii. disadvantages of an undetermined generic type

1. Report warning, no in-generic parameterization

2. Do not define generics, the collection can be loaded into any type of object, which is not safe

3. To take the data in the collection, a strong turn

Import Java.util.iterator;import Java.util.set;import Java.util.treeset;public class Test {public    static void main (string[] args) {        Set treeSet = new TreeSet ();//No generics are used, so:set<student> treeSet = new treeset<student> ();        Treeset.add (New Student (11, 80, "Li Ping"));        Treeset.add (New Student (23, 40, "Wang Fang"));        Treeset.add (New Student (10, 60, "Zhao Lei"));        Treeset.add (New Student (12, 40, "Wangxiao"));        Treeset.add (New Student (10, 60, "Ma Miao"));        Treeset.add (New Student (18, 60, "Ma Miao"));        Treeset.add (New Student (25, 70, "Jiang Hao"));        Iterator it = Treeset.iterator ();        while (It.hasnext ()) {            Student stu = (Student) it.next ()//Not using generics: Requires a strong turn            System.out.println (stu);        }    }}

Start error at compile time (yellow):

After modification:

Note: The generic type must be a reference type!!!

Note: The generic type must be a reference type!!!

Note: The generic type must be a reference type!!!

III. Formulation of generic types

In the JDK we often see the following three cases:

1.TreeSet (collection<? extends e> c)

2.TreeSet (comparator<? Super E> Comparator)

3.TreeSet (sortedset<e> s)

which

? Wildcard, which refers to any data type

< > refers to generics. (as you can see, 3 is the normal definition of generics)

The following note:

Limit limit for generics: <? Extends e >//means receiving E for this type, or subtype of E
Limited limit for generics: <? Super e >//means receive e this type, or E's parent type

code example:

This function can only receive number and its subclass    static void Show (POINT<? extends number> p) {         System.out.println (P.getx ());        System.out.println (P.gety ());    }        public static void Main (string[] args) {/        * for the above declaration, the following operation is possible        point<integer> p1=new point<integer> ();        P1.setx (new Integer);        P1.sety (new Integer);        Show (p1);      *                ///The following operation will be error        point<string> p1=new point<string> ();        P1.setx ("90ok");        P1.sety ("50ok");        Show (p1); Error
Class test7{    //This function can only receive number and its subclass    static void Show (POINT<? Super String> P) {         System.out.println ( P.getx ());        System.out.println (P.gety ());    }        public static void Main (string[] args) {      /* Here will be an error        point<integer> p1=new point<integer> ();        P1.setx (new Integer);        P1.sety (new Integer);        Show (p1);      *                  /point<string> p1=new point<string> ();        P1.setx ("90ok");        P1.sety ("50ok");        Show (p1);  Yes    }}

(Image from Network)

Iv. Understanding the application of generics

We can customize generic classes, generic methods, and generic interfaces. Learning needs to know its principles, and then you can happily call the JDK inside the ~ ~

1. Custom generic Classes

Class Objectfactory<t> {//Declaration generic <T>    private T obj;    Public T Getobj () {        return this.obj;    }    public void Setobj (T obj) {        this.obj = obj;    }     /* * The following notation does not set public T getnewobj () {T t=new t ();//At compile time, cannot determine the parameterized type of generics return     * T;     */}class Test4 {public    static void Main (string[] args) {        //List list=new ArrayList ();        /         * * objectfactory f=new objectfactory (); F.setobj ("ss")         ; *        /objectfactory<string> f = new objectfactory<string> ();        F.setobj ("This must be a string");        F.setobj (89); Cannot be        String obj = F.getobj ();        System.out.println (obj);        objectfactory<student> stulist = new objectfactory<student> ();        Stulist.setobj (New Student (67, 90, "Zhang San"));        Stulist.getobj (). speak ();    }}

2. Generic methods

public class Testfan {        //generic method, no restrictions here, pass anything can be public    <T> void Show (T t) {        System.out.println ("This is a generic method "+ t);}    } Class Test5 {public    static void Main (string[] args) {        Testfan Tfan = new Testfan ();                Tfan.show ("777");                Tfan.show (898);                Tfan.show (New Student (30, 20, "cat"));}    }

3. Generic interface

V. Generic Limitations

1. You cannot create an instance with a generic parameter, that is, you cannot use the new E ()

2. The exception class cannot be generic

3. The parameter of the class is not allowed in the static environment is a generic type (note)

Because all instances of a generic class have the same run-time class, the static variables and methods of the generic class are shared by all instances of it. Since it is shared, there is no need to redefine the same generic type, and if you do not define the same generic type, it is not shared (or consistent), and it is not necessary to let that happen. Therefore, in the static environment, the parameters of the class are set to generic non-law.

public class Ee<e> {public        static E Example1;  Illegal public    static void Example2 (E O1) {                 //illegal    }    static {        e Example3;//Illegal    }}

Java Basics-Generics

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.