Summary of Java generic usage methods

Source: Internet
Author: User

1. Basic Concepts:
(1) What is a generic type?
Generic, which is the parameterized type. The type is parameterized by the original specific type, similar to the variable parameter in the method, at which time the type is also defined as a Parameter form (which can be called a type parameter) and then passed into the specific type (type argument) when used or called.

(2) Why generics are used?
The essence of generics is to control the type of the formal parameter restriction by the different types specified by the generic type, without creating a new type.
That is, during generics use, the data type of the operation is specified as a parameter, which can be used in classes, interfaces, and methods, respectively, as generic, generic, generic.

2. Features:

Refer to the following code:

public class Generictest {public    static void Main (string[] args) {        list<string> list1 = new Arraylist<st Ring> ();        list<integer> list2 = new arraylist<integer> ();        Class Class1 = List1.getclass ();        Class Class2 = List2.getclass ();        System.out.println (Class1.equals (Class2)); Returns True    }}

After compiling, the program takes steps to generics. This means that generics in Java are only valid during the compilation phase. When a generic result is correctly inspected during compilation, the information about the generic is erased and methods of type checking and type conversion are added at the boundary of the object's entry and exit methods. In other words, generic information does not go into the runtime phase.
Therefore, generic types are logically viewed as multiple different types, and are actually the same basic types.

3. Use:
(1) generic type:

public class Generic<t> {    private T key;    Public Generic (T key) {        This.key = key;    }    Public T GetKey () {        return key;    }    public void Setkey (T key) {        This.key = key;    }} public static void Main (string[] args) {    Generic Ginteger = new Generic (123);    Generic gstring = new Generic ("abc");    System.out.println (Ginteger.getkey ()); 123    System.out.println (Gstring.getkey ());  "ABC"}

(2) Generic interface:

Public interface Generator<t> {    T getName ();} public class Integergenerator implements Generator {    @Override public    Object getName () {        return 123;  Returns the integer type    }}public class Stringgenerator implements Generator {    @Override public    Object GetName () {        return "Apple";  Returns the string type    }}stringgenerator SGenerator1 = new Stringgenerator (); Integergenerator IGenerator1 = new Integergenerator (); System.out.println (Sgenerator1.getname ());   "Apple" System.out.println (Igenerator1.getname ());   123

(3) Generic method:

public class Genericmethod {static class fruit{@Override public String toString () {return "        Fruit ";        }} static Class Apple extends fruit{@Override public String toString () {return ' Apple ';        }} static Class person{@Override public String toString () {return ' person '; }} static class generatemethodtest<t>{public void Show_1 (T t) {SYSTEM.OUT.PRINTLN (T.tos        Tring ()); }//A generic method is declared in a generic class, using generic E, which can be any type.        Can be of the same type as T, or it can be different.        Because generic methods declare generic &LT;E&GT when declared, the compiler can correctly recognize generics that are recognized in generic methods, even if generics are not declared in a generic class.        Public <E> void Show_3 (E t) {System.out.println (t.tostring ());        }//Declare a generic method in a generic class, using generic T, note that this T is a completely new type and can not be the same type as the T declared in the generic class.        Public <T> void Show_2 (T t) {System.out.println (t.tostring ());        }} public static void Main (string[] args) {Apple Apple = new Apple ();person person = new person ();                generatemethodtest<fruit> generatetest = new generatemethodtest<fruit> (); Generatetest.show_1 (apple);//apple is a subclass of fruit, so this can be//generatetest.show_1 (person);//the compiler will error because generic type arguments specify fruit,        And the passed-in argument class is the person//use both methods can be successful generatetest.show_2 (Apple);        Generatetest.show_2 (person);        Both of these methods can also be successful generatetest.show_3 (Apple);    Generatetest.show_3 (person);  }}

(4) Generic wildcard characters:
Integer is a subclass of number, can I pass in Generic<integer> 's arguments in a method that uses generic<number> as a formal parameter? Is it logical whether generic<number> and generic<ingeter> are generic types of parent-child relationships?

public class Genericwildcard {    static void Showvalue (generic<number> number) {        System.out.println ( Number.getkey ());    }    public static void Main (string[] args) {        generic<integer> igeneric = new generic<integer> (ten);        generic<number> ngeneric = new generic<number> (+);        Showvalue (igeneric);//Compile error:generic<java.lang.integer> cannot be applied to generic<java.lang.number>        Showvalue (ngeneric);    }}

The above example shows that,generic<integer> cannot be considered a subclass of generic<number>, that is, the same generic can correspond to multiple versions, and different versions of generic instances are incompatible. Then you need to introduce the concept of wildcards to solve this problem, as follows:

public class GenericWildcard1 {    static void showValue1 (Generic<?> obj) {        System.out.println (Obj.getkey ( ));    }    public static void Main (string[] args) {        Generic iGeneric1 = new Generic (ten);        Generic NGeneric1 = new Generic (+);        ShowValue1 (IGENERIC1);        ShowValue1 (NGENERIC1);    }}

(5) The upper and lower bounds of the generic type:

public class Genericwildcard {    static void showValue2 (GENERIC<? extends number> obj) {        System.out.println (Obj.getkey ());    }    public static void Main (string[] args) {        generic<integer> Ginteger = new Generic (+);        generic<double> gdouble = new Generic (10.0);        generic<float> gfloat = new Generic (1.1f);        generic<string> gstring = new Generic ("abc");        ShowValue2 (Ginteger);        ShowValue2 (gdouble);        ShowValue2 (gfloat);        ShowValue2 (gstring); This line of code compiler will prompt for an error because the string type is not a subclass of number type    }}

Summary: The upper and lower bounds of generics are added and must be declared with generics.

(6) Generic array:
You cannot create an array of the exact generic type in Java, as in the following example:

list<string>[] List1 = new arraylist<string>[10]; Compilation does not pass object[] obj = (object[]) List1; list<integer> list2 = new arraylist<integer> (); List2.add (new Integer); obj[1] = List2;integer str1 = List1[0].get (1); Run-time error:classcastexception.

At this time, because of the JVM generic erase mechanism, the JVM is not aware of the generic information at runtime, so you can give obj[1] a ArrayList without exception, but when fetching data does not do type conversion, so there will be run-time error: ClassCastException. If you can make a declaration of a generic array, there will be no warnings and errors at compile time for this scenario, as follows:

list<?>[] list11 = new arraylist<?>[10];object[] Obj1 = (object[]) list11; list<integer> list22 = new arraylist<integer> (); List22.add (new Integer); obj1[1] = List22;integer Integer = (integer) list11[1].get (0);

  

Reference: http://blog.csdn.net/myself8202/article/details/74911227

Summary of Java generic usage methods

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.