Understanding of Java Generics

Source: Internet
Author: User
Tags addall comparable

Recently watching video, see more classic than the size of the problem. Enter two numbers, return a large number, type can be int,long,float, etc.

The general tutorial uses this example to introduce the concept of constructors and overloading, and after learning generics, I think I can write a generic method for comparison.

To accomplish this task, we first need to understand generics.

What's generics

Generics are an extension of the Java language System and support the creation of classes that can be parameterized by type.

Benefits of Generics

The benefits of generics are also obvious,

The generality of the code can be expanded first, and the generic type allows the method to support more types.

Generics help to enhance type safety, and the compiler can interpret types more accurately.

Generics help reduce the type cast and reduce the chance of error.

We need to master what usage of generics

You need to master the usage of generic interfaces, generic classes, generic methods in generic classes, generic methods in non-generic classes, type wildcards, and upper and lower bounds of type wildcard characters.

Generic interface

A good example of a generic interface is that E in java.util.list.class,<e> is a type parameter and can receive concrete types of arguments. The place where E appears in the interface is the concrete type of argument that is received.

 PackageJava.util; Public Abstract InterfaceList<e>extendsCollection<e>{   Public Abstract intsize ();  Public Abstract BooleanIsEmpty ();  Public Abstract Booleancontains (Object paramobject);  Public AbstractIterator<e>iterator ();  Public Abstractobject[] ToArray ();  Public Abstract<T>t[] ToArray (t[] paramarrayoft);  Public Abstract BooleanAdd (E ParamE);  Public Abstract BooleanRemove (Object paramobject);  Public Abstract BooleanContainsall (collection<?>paramcollection);  Public Abstract BooleanAddAll (collection<?extendsE>paramcollection);  Public Abstract BooleanAddAll (intParamint, collection<?extendsE>paramcollection);  Public Abstract BooleanRemoveAll (collection<?>paramcollection);  Public Abstract BooleanRetainall (collection<?>paramcollection);  Public Abstract voidClear ();  Public Abstract Booleanequals (Object paramobject);  Public Abstract inthashcode ();  Public AbstractE Get (intparamint);  Public AbstractE Set (intParamint, E ParamE);  Public Abstract voidAddintParamint, E ParamE);  Public AbstractE Remove (intparamint);  Public Abstract intindexOf (Object paramobject);  Public Abstract intlastIndexOf (Object paramobject);  Public AbstractListiterator<e>Listiterator ();  Public AbstractListiterator<e> Listiterator (intparamint);  Public AbstractList<e> sublist (intParamInt1,intparamInt2);}

Generic class

Generic classes are defined in a way similar to interfaces

 Public classArraylist<e>extendsAbstractlist<e>ImplementsList<e>, Randomaccess, cloneable, java.io.serializable{Private Static Final LongSerialversionuid = 8683452581122892189L; /*** The array buffer into which the elements of the ArrayList is stored.     * The capacity of the ArrayList is the length of this array buffer. */    Private transientobject[] Elementdata;  PublicArrayList (collection<?extendsE>c) {Elementdata=C.toarray (); Size=elementdata.length; //C.toarray might (incorrectly) not return object[] (see 6260652)    if(Elementdata.getclass ()! = object[].class) Elementdata= arrays.copyof (elementdata, size, object[].class); }         PublicE Set (intindex, E Element)    {Rangecheck (index); E OldValue=(E) Elementdata[index]; Elementdata[index]=element; returnOldValue; }    }

Generic methods in generic classes

For example, the set method above is used to represent the type argument directly with E.

Generic methods in non-generic classes

A generic declaration needs to be preceded by a method modifier before returning a value.

class test{    publicvoid  paly (T a) {        System.out.println (A.getclass ());}    }

Type wildcard character

The following test methods can be used to better reflect the use of type wildcard characters:

Box.java

 Public class Box<t>{    private  T box;          Public T Getbox () {        return  box;    }      Public void Setbox (T box) {        this. box = box;    }       Public Box (T a) {        setbox (a);    }}

Boxmain.java

 Public classBoxmain {/**     * @paramargs*/     Public Static voidMain (string[] args) {Box<Integer> test1 =NewBox<integer> (111); Box<String> test2 =NewBox<string> ("AAA");        SHOW3 (test1);                SHOW4 (TEST2);        Show1 (test1);                Show1 (TEST2);        Show2 (test1);    Show2 (TEST2); }         Public Static<T>voidShow1 (box<t>a)            {System.out.println (A.getbox ()); }         Public Static voidShow2 (box<?>a)        {System.out.println (A.getbox ()); }         Public Static voidSHOW3 (box<integer>a) {System.out.println (A.getbox ()); }         Public Static voidSHOW4 (box<string>a) {System.out.println (A.getbox ()); }}

Where the Show1 method is a generic method in a non-generic class, Show2 uses the type wildcard character, SHOW3 and show4 are useless. It can be seen that the use of type wildcards can replace the SHOW3 and Show4 methods, which is more convenient.

Upper and lower bounds for type wildcard characters

Where this type of wildcard is used, we sometimes need to make such a restriction when considering its type: The type wildcard represents a type that requires a restriction, such as a subclass of test or test, which must be the parent class of test or test.

We're going to use it here.

? Extends Test

? Super Test

These two kinds of writing, Which? Extends test indicates that it must be a subclass of test or test, called the upper bound of a type wildcard.

? The super test indicates that the parent class must be test or test, which is called the lower bound of the type wildcard.

At this point, we have completed the generic type of learning, the following we completed the first question, with the generic comparison size.

Returnbig.java

 PackageCom.fan; Public classReturnbig <textendsComparable<t>>{     PublicT A;  PublicT B;  PublicT Geta () {returnA; }     Public voidSetA (T a) { This. A =A; }     PublicT Getb () {returnb; }     Public voidSetb (T b) { This. B =b; }     Public intcompareTo (T o) {returnA.compareto (o); }         PublicReturnbig (T a,t b) {SetA (a);    Setb (b); }         PublicT returnbigt () {if(CompareTo (b) >0) {            returnA; }Else{            returnb; }    }}

Fanmain.java

 PackageCom.fan; Public classFanmain { Public Static voidMain (string[] args) {//comparison size is relatively limited compared to a little more, if it is sentenced, and so much simpler. Returnbig<integer> Returnbig =NewReturnbig<integer> (11,22); System.out.println ("The Big num is:" +returnbig.returnbigt ()); Returnbig<Float> RETURNBIG1 =NewReturnbig<float> (11.11f,22.11f); System.out.println ("The Big num is:" +returnbig1.returnbigt ()); }    }

The comparable interface is used here, and it is important to note that the class that implements the comparable interface is limited, and the comparison of any two objects is meaningless. Only specific types of comparisons make sense.

Understanding of Java 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.