Java Generic Programming

Source: Internet
Author: User

1. Generic class

A generic class is a class that has one or more type variables, and a large number of generic classes are used in the Java Collection framework. Generic programming enables the code to be shared by many different types, greatly improving the reusability of the code.

The following is an example of a custom generic class:

 Public classPair<t>{   PrivateT first; PrivateT Second;  PublicPair (T first,t second) { This. First =First ;  This. Second =second; }   PublicT GetFirst () {returnFirst ; }     PublicT Getsecond () {returnsecond; }  Public voidSetfirst (T first) { This. First =First ; }    Public voidSetsecond (T second) { This. Second =second;} }

You can instantiate a generic type by replacing the type variable T with a normal class name, such as: Pair<string>,java generic classes are similar to C + + template classes.

2. Generic methods

Java can also define methods with type parameters, that is, generic methods, which can be defined in a generic class or in a normal class.

 Public class arrayhelper{    publicstatic <T> T getmiddle (t[] array)    {         return ARRAY[ARRAY.LENGTH/2];}    }

The generic method described above, the parameter is a generic array, the return value is a generic variable, followed by the modifier <T> indicates that this is a generic method. When invoking a generic method, the "<>" in front of the method name adds a specific type, such as: Arrayhelper.<string>getmiddle (New string[]{"left", "middle", "right"}), In fact, most of the cases can also be omitted <String>.

3. Qualification of type variables

Sometimes we want to be able to use different types, but we want this type to satisfy certain constraints, which depends on the qualification of the type variable.

 Public class arrayhelper{  publicstatic <T> T max (t[] array)  {       t  = Array[0];        for (int i = 1; i <  array.length; i++)        if(Array[i].compareto (max) > 0 )         = Array[i];
return max;} }

We want to use the CompareTo method to compare each element in a generic array to select the largest element, which requires that the type must implement the comparable interface, and we can qualify the type variable t as follows:

 Public class arrayhelper{  publicstaticextends comparable> T max (t[] array)  {       T   = Array[0];        for (int i = 1; i <  array.length; i++)        if(Array[i].compareto (max) > 0 )         = Array[i];
return max;} }

A type variable can have multiple qualifications, such as: <t extends comparable & serializable>.

4. Type Erase

After we have defined a generic type, we can adapt to a variety of different types, but in fact the virtual machine only knows one primitive type, for example, for the above definition of PAIR<T>, the corresponding primitive type is as follows:

 Public classpair{PrivateObject first; PrivateObject Second;  PublicPair (Object first,object second) { This. First =First ;  This. Second =second; }   PublicObject GetFirst () {returnFirst ; }     PublicObject Getsecond () {returnsecond; }  Public voidSetfirst (Object first) { This. First =First ; }    Public voidSetsecond (Object second) { This. Second =second;} }

To replace T with the object class, you are actually replacing T with a qualified type. Assuming <t extends Comparable>, the T is replaced with a comparable, and if there are more than one qualified type, it is replaced with the first qualified type. If there is no qualifying type, it is replaced with the object class, which is the type erase.

Therefore, a generic class is compiled into a byte-code.

5. Inheritance rules for generic classes

(1) Suppose there is a print method for printing an employee pair, the parameter is pari<employee>

 Public void print (pair<employee>) {   ...}

The Manager class is a subclass of the Employee class, so is pair<manager> a subclass of pair<employee>? , can you pass in the Print method? The answer is no.,pair<manager> is not a pair<employee> subclass.

(2) The parameterized type can always be converted to the original type, such as: Pair pair = new pair<manager> ("Jack", "Mike"); This is to keep up with the legacy code that precedes generics.

(3) Generic classes can inherit other classes like normal classes, implementing interfaces. such as: Class Pair<t> implements comparable.

6. Wildcard Type

pair<? Extends fruit> represents any generic pair type whose type parameter is a subclass of Fruit. Pair<fruit> and pair<apple> are pair< Extends subtype of fruit>.

pair<? Super apple> represents any generic pair type whose type parameter is Apple's parent class. Pair<fruit> and pair<object> are pair< The subtype of Super apple>.

In this way, you can use the parameter polymorphism to modify the Print method above:

Public void print (pair<? extends fruit>) {   ...}

It is now possible to pass in pair<apple> and pair<banana> as parameters.

However, when using a parent class variable to refer to a subclass instance for polymorphism of the wildcard type, you need to be aware of the following issues:

pair<apple>  New pair<apple>, new Apple ("Apple1"),new Apple ("Apple2"  )); Pairextends fruit>  fruits = apples; // The following two sentences call the Setfirst method to compile the error, because the compiler only know that the type of the pair is the subclass of the fruit, but do not know what the specific type. Fruits.setfirst (new Apple ("Apple3"));    Fruits.setfirst (new Banana ("Banana1")); // The following call to the GetFirst method does not make an error because the compiler knows that the type saved in the pair must be a subclass of fruit, and converting to the fruit class will not be an error. Fruit First  = Frutis.getfirst ();

That is, for < Extends type> wildcard type, when you reference a subclass instance using a parent class variable, you cannot write to the child class instance and read only.

 pair<apple> apples = new  pair<apple> (new  Apple ("Apple1"), new  Apple ("Apple2"  <? super  apple> fruits = apples;   Fruits.setfirst (new  goodapple ("Apple3" //   This sentence calls the Setfirst method without error because the compiler knows that the type saved in the pair must be the parent class of the Apple class, so Incoming Apple class objects, or child class objects of the Apple class, are available  
fruits.setfirst ( new Fruit ("Banana1" )); //the parent class object that passed into the Apple class compiles an error
Fruit first = Frutis.getfirst (); //compilation does not pass because the compiler knows that the type saved in the pair is the parent class of the Apple class, but does not know what the specific class is, so you can only assign the variable
to the object class.

That is, for < Super Type> wildcard type, when you reference a subclass instance using a parent class variable, you cannot read the child class instance and write only.

Java Generic Programming

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.