The various uses of generics in Java

Source: Internet
Author: User

Use of generics in Java:
1. Common generic Use

The type that follows <> in the use of the class is the type we determine.

public class Myclass1<t> {//The generics defined here are T-    private t var;    Public T GetVar () {        return var;    }    public void SetVar (T var) {        This.var = var;    }} /** * Most common generics use, only one generic type */@Testpublic void TestMyClass1 () {    myclass1<string> clazz = new myclass1<string > ();//This determines that the generic t corresponding to the object is a string    clazz.setvar ("StringType");    String str = Clazz.getvar ();    System.out.println (str);}


2. With two generic types

As with normal generics, it's just that we can define two different generic types when using classes, and of course we can define multiple as long as our business needs.

public class Myclass2<k, v> {///here defines two generic types    private K var1;//The type of the first variable is the specific type of k corresponding to the    private V var2;// The type of the second variable is the specific type of v corresponding to public    K getVar1 () {        return var1;    }    public void SetVar1 (K var1) {        this.var1 = var1;    }    Public V getVar2 () {        return var2;    }    public void SetVar2 (V var2) {        this.var2 = var2;    }} /** * contains two generic types with the use of */@Testpublic void TestMyClass2 () {    ///here to determine the defined Clazz object's first generic type is integer, the second generic type is string    Myclass2<integer, string> clazz = new Myclass2<integer, string> ();    CLAZZ.SETVAR1 (1); Only parameter Clazz.setvar2 ("string") of type int can be used here,    or only    System.out.println (clazz.getvar1 () + "," + CLAZZ.GETVAR2 ());}


3. Generics with wildcard characters

There are also 3 types: Unlimited wildcard characters, using extends restrictions, using super restrictions

public class Myclass3<t> {private T var;    Public T GetVar () {return var;    } public void SetVar (T var) {this.var = var;    } @Override Public String toString () {return var.tostring (); }}/** * wildcard characters? The use includes <?>, < Extends type > and <?    Super Type > */@Testpublic void TestMyClass3 () {myclass3<boolean> clazz = new myclass3<boolean> ();    Clazz.setvar (FALSE);    Fun (clazz);//When dispatching this method, there is no restriction on generics, and any type of generics can use myclass3<integer> clazzint = new myclass3<integer> ();    Clazzint.setvar (1); Funextends (clazzint);//When you are dispatching this method, you can only use the number type or its subtype myclass3<double> clazzdouble = new Myclass3<double> (    );    Clazzdouble.setvar (2.2); Funextends (clazzdouble);//When you are dispatching this method, you can only use the number type or its subtype myclass3<string> clazzstring = new myclass3<string    > ();    Clazzstring.setvar ("string"); Funsuper (clazzstring);//When you are dispatching this method, you can only use the string type or its parent type myclass3<object> Clazzobject = new myclass3<object> ();    Clazzobject.setvar (New Object ());    Funsuper (clazzobject);//When you are dispatching this method, you can use only the string type or its parent type}public void Fun (myclass3<?> clazz) {//Unrestricted generics use System.out.println (clazz);} public void Funextends (myclass3<? extends number> Clazz) {//Only generic System.out.println (Clazz) of number and its subclasses can be used;} public void Funsuper (MYCLASS3&LT;? Super String> Clazz) {//can only use the generic System.out.println (clazz) of String and its parent class;}


4. Restrict generics when defining classes

public class Myclass4<t extends Number> {//defines the generic type of the class when generics are limited to the    private T var;    Public T GetVar () {        return var;    }    public void SetVar (T var) {        This.var = var;    }    @Override public    String toString () {        return this.var.toString ();    }} /** * Defines the generics of a class with the restriction of a given generic type/@Testpublic void TestMyClass4 () {//    the same can only define the generics    //myclass4<string> of number and its subclasses clazzstring = new myclass4<string> ();    myclass4<integer> clazzint = new myclass4<integer> ();    myclass4<double> clazzdouble = new myclass4<double> ();    Myclass4<float> clazzFClass4 = Fun (1.1f);    The parameter for dispatching here is the float type, which determines that the return type must be Float}public <t extends number> myclass4<t> fun (T Arg) {    return new Myclass4<t> ();}


5. Use of generic interfaces

Public interface Myinterface<t> {public T GetVar ();} Two ways to achieve this.    1, in the implementation of the use of generics, to the specific definition of the object, then determine the public class Myinterface1impl<t> implements myinterface<t> {private T var;    Public Myinterface1impl () {} public Myinterface1impl (T var) {this.var = var;    } @Override Public T GetVar () {return this.var;    }}//the second implementation, at the time of implementation to determine the generic type of public class Myinterface2impl implements myinterface<string> {private String varstr;    Public Myinterface2impl () {} public Myinterface2impl (String varstr) {this.varstr = Varstr;    } @Override Public String GetVar () {return this.varstr;  }}/** * Generic interface use */@Testpublic void Testmyinterface () {///implementation class can be defined as any type of generic myinterface1impl<string> varstr = new    Myinterface1impl<string> ("abc");    System.out.println (Varstr.getvar ());    myinterface1impl<integer> varint = new myinterface1impl<integer> (123);    System.out.println (Varint.getvar ()); has been implemented in the class beforeThe time has been determined to be only string myinterface2impl var = new Myinterface2impl ("CBA");    String str = Var.getvar (); System.out.println (str);}


6. Use of generic methods

public class MyFunction {public <T> t fun1 (t arg) {//Incoming parameters and return parameters are all the same generic type return arg; } public <T> void Fun2 (T arg) {//passed in parameter is generic and does not need to return if (Arg instanceof String) {System.out.println (        "T is StringType");        } else if (arg instanceof Integer) {System.out.println ("T is Integertype");        } else {System.out.println ("T is Othertype");    }} public <T> String fun3 (T arg) {//The passed in parameter is generic and returns the determined type return arg.tostring ();        }}/** * Use of the generic method */@Testpublic void MyFunction () {MyFunction clazz = new MyFunction ();    What type is passed in, what type of String var1 = CLAZZ.FUN1 ("abc") is returned;    int var2 = CLAZZ.FUN1 (12);    System.out.println (VAR1);    System.out.println (VAR2);    No matter what type of incoming, it's okay clazz.fun2 (1);    Clazz.fun2 (FALSE);    Clazz.fun2 ("string");    Regardless of what is passed in, the string string var3 = Clazz.fun3 (123) is returned;    String VAR4 = Clazz.fun3 ("string");    System.out.println (VAR3); System.out.println (VAR4);}


7. Generic arrays

/** * Use of a generic array */@Testpublic void Testarray () {integer[] arr = fun (All-in-a--    );   } Public <T> t[] Fun (t ... args) {//incoming what type, T is what type, and can use generic traversal for    (t T:args) {        System.out.println ( T.tostring ());    }    return args;}

8. Nested generics

/** * Nested generics */@Testpublic void testnest ()    the type of the generic is the inner generic, and when the inner-layer generics are determined, the outer generics are determined    myclass1<myclass2< Integer, string>> nestout = new myclass1<myclass2<integer,string>> ();    Myclass2<integer, string> nestIn = new myclass2<integer,string> ();    NESTIN.SETVAR1 (1);    NESTIN.SETVAR2 ("a");    Nestout.setvar (nestIn);    System.out.println (Nestout.getvar (). GETVAR1 ());    System.out.println (Nestout.getvar (). GETVAR2 ());}

    • Genericity.rar (3.1 KB)
    • Download number of times: 6

The various uses of generics in Java

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.