Java know how much (42) the range of generic wildcard characters and type parameters

Source: Internet
Author: User
Tags gety

This section first explains how to limit the scope of a type parameter and then explain the wildcard character (?). The scope of a type parameter is in a generic, and if the type parameter is not restricted, it can accept any data type as long as it is defined. However, many times we only need a subset of the data types to be sufficient, and the user passing other data types can cause errors. For example, write a generic function that returns the maximum value in an array of different types (an Integer array, a Double array, and so on):
 1  public  <t> T Getmax (T array[]) { 2  T max = null   3   (T Element:array) { 4  max = Element.doublevalue () > Max.doublevalue () ?  Element:max;  5   6  return   Max;  7 } 

The above code will give an error, Doublevalue () is the method of the number class and its subclasses, not all classes have the method, so we want to limit the type parameter T, so that it can only accept number and its subclasses (Integer, Double, Character, etc.).


The extends keyword allows you to limit the type of generics to the upper limit, improving the above code:
 1  public  <t extends  number> T Getmax (T array[]) {  2  T max = null  ;  3   (T Element:array) { 4  max = Element.doublevalue () > Max.doublevalue () ?  Element:max;  5   6  return   Max;  7 } 

<t extends number> means that T accepts only number and its subclasses, and passing in other types of data will cause an error. The limit here is extends with the keyword, which can be either a class or an interface. If it is a class, there can only be one, but the interface may be multiple and separated with "&", for example <t extends Interface1 & interface2>.


The extends keyword here is no longer the meaning of inheritance, it should be understood that T is a type that inherits from the number class, or T is the type that implements the XX interface. wildcard character (?) The example in the previous section mentions that to define a generic class to represent coordinates, which can be integers, decimals, or strings, see the following code:
1 classPOINT&LT;T1, t2>{2 T1 x;3 T2 y;4      PublicT1 GetX () {5         returnx;6     }7      Public voidSetX (T1 x) {8          This. x =x;9     }Ten      PublicT2 GetY () { One         returny; A     } -      Public voidsety (T2 y) { -          This. y =y; the     } -}
Now it is required to define a Printpoint () method outside the class for output coordinates.

You can define methods like this:
1  Public void printpoint (point P) {2     System.out.println ("This point is:" + p.getx () + "," + p.gety ()); 3 }

We know that if you do not specify a specific data type when using generics, you will erase the generic type and move up to Object, which is no different from using generics. The above code does not indicate the data type, which is equivalent to:

1  Public void printpoint (point<object, object> p) {2     System.out.println ("This Point is: "+ p.getx () +", "+ p.gety ()); 3 }

To avoid type erasure, you can use a wildcard character (?) :

1  Public void printpoint (point<?,? > p) {2     System.out.println ("This point is:" + p.getx () + "," + p.gety ()); 3 }

wildcard character (?) can represent any type of data. Add the Code complete:

1  Public classDemo {2      Public Static voidMain (string[] args) {3Point<integer, integer> p1 =NewPoint<integer, integer>();4P1.setx (10);5P1.sety (20);6 Printpoint (p1);7       8point<string, string> p2 =NewPoint<string, string>();9P2.setx ("Tokyo 180 Degrees");TenP2.sety ("Latitude 210 degrees"); One printpoint (p2); A     } -     -      Public Static voidPrintpoint (point<?,? > P) {//using wildcard characters theSystem.out.println ("This point is:" + p.getx () + "," +p.gety ()); -     } - } - classPOINT&LT;T1, t2>{ + T1 x; - T2 y; +      PublicT1 GetX () { A         returnx; at     } -      Public voidSetX (T1 x) { -          This. x =x; -     } -      PublicT2 GetY () { -         returny; in     } -      Public voidsety (T2 y) { to          This. y =y; +     } -}

Operation Result:

This point is:10, 20
This is: Tokyo 180 degrees, latitude 210 degrees

However, there is a difference between numeric coordinates and string coordinates: numbers can represent the coordinates of the x-axis or y-axis, and the string can represent the latitude and longitude of the Earth. Now it is required to define two methods to deal with different coordinates, one method can only accept the coordinates of the numeric type, and the other method can only accept the coordinates of the string type.

The key to this problem is to limit the range of type parameters, first look at the following code:
1  Public classDemo {2      Public Static voidMain (string[] args) {3Point<integer, integer> p1 =NewPoint<integer, integer>();4P1.setx (10);5P1.sety (20);6 Printnumpoint (p1);7       8point<string, string> p2 =NewPoint<string, string>();9P2.setx ("Tokyo 180 Degrees");TenP2.sety ("Latitude 210 degrees"); One printstrpoint (p2); A     } -     -     //limit the scope of generics with wildcards the      Public Static voidPrintnumpoint (point<?extendsNumber,?extendsNumber>p) { -System.out.println ("x:" + p.getx () + ", Y:" +p.gety ()); -     } -     +      Public Static voidPrintstrpoint (point<?extendsString,?extendsString>p) { -System.out.println ("GPS:" + p.getx () + "," +p.gety ()); +     } A } at classPOINT&LT;T1, t2>{ - T1 x; - T2 y; -      PublicT1 GetX () { -         returnx; -     } in      Public voidSetX (T1 x) { -          This. x =x; to     } +      PublicT2 GetY () { -         returny; the     } *      Public voidsety (T2 y) { $          This. y =y;Panax Notoginseng     } -}

Operation Result:

X:10, y:20
GPS: Tokyo 180 degrees, latitude 210 degrees

? Extends number indicates that the generic type parameter can only be number and its subclasses,? Extends String, too, is similar to restricting the scope of a type parameter when defining a generic class or generic method.

However, use wildcard characters (?) Not only can you limit the upper limit of the type, but you can also limit the lower. Restrict the lower limit to use the Super keyword, such as <? Super number> indicates that only number and its parent can be accepted.

Note: The general project rarely to design generics, here is mainly to let the reader learn how to use, for the next tutorial to pave the way. Series Articles:

Java know how much (top)

Java know how much (interface) interface

Java knows how much (40) the difference between an interface and an abstract class

Java know how much (41) generic explanation

Java know how much (42) the range of generic wildcard characters and type parameters

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.