Generic wildcard characters and bounded type parameters in Java

Source: Internet
Author: User
Type wildcard character

Type wildcard characters are generally used instead of specific type arguments ( Here are type arguments, not type parameters ). When you do not need to use the type's specific functionality when manipulating types, you can use only the functions in the object class. Wildcard character table unknown type. For example, list<?> is logically the parent class of all list< concrete type arguments >, such as list<string>, list<integer>, and so on.

public class Generictest {public static void main (string[] args) {list<string> name = new arraylist& Lt        String> ();        list<integer> age = new arraylist<integer> ();           list<number> number = new arraylist<number> ();        Name.add ("ZWJ");        Age.add (18);           Number.add (120); Getnumberdata (age); Error Getnumberdata (number);  GetData (name); ZWJ GetData (age); GetData (number); //getupernumber (name); An error has occurred and the parameter in the method has qualified the parameter generic limit to number getupernumber (age); Getupernumber (number); 120}/** * In a method that uses list<number> as a formal parameter, you cannot use an instance of list<ingeter> to pass in, which means that list<integer&gt As a subclass of list<number>; */public static void Getnumberdata (list<number> data) {SYSTEM.OUT.PRINTLN    ("Data:" + data.get (0));     /** * Use a type wildcard to represent both list<integer> and list<number> reference types. * Type wildcard characters are generally used instead of specific type arguments, note that this is a type argument; * and number, String, integer is an actual type, you can put?     As a parent class for all types.    */public static void GetData (list<?> data) {System.out.println ("Data:" + data.get (0));     The upper bound of the/** * type wildcard is defined by a shape such as list, which is defined as a wildcard generic value that accepts number and its underlying subclass type. */public static void Getupernumber (LIST&LT;? extends number> data) {System.out.println ("Data:" + data.ge    T (0)); }}

bounded type parameters

Sometimes we want to limit the range of types that are allowed to be passed to a type parameter. For example, a method that operates on numbers may only want to accept instances of the number or a child class. At this point the monkey needs to add the upper boundary for the generic type, that is, the type argument passed in must be a subtype of the specified type.

To declare a bounded type parameter, first list the name of the type parameter, followed by the extends or Super keyword, and then immediately following its upper or lower bounds. This allows you to know that the addition of the upper and lower bounds of a generic must be declared with the generic.

< extends t> indicates that the wildcard represents a subclass of type T. For example, when you add an element to a collection, you can either add an E type object, or you can add a subtype object of E. Why? Because the E type can receive both the Class E object and the subtype object of E.

< Super T> indicates that the type represented by the wildcard is the parent class of type T. For example, when an element is taken from a collection, it can be received with the current element's type, or it can be received with the parent type of the current element.

public class Genericmethodtest {    //compares three values and returns a maximum of public    static <t extends comparable<t>> T getmaxnuum (t x, t y, T Z) {                             T max = x;//Assuming X is the initial maximum        if (Y.compareto (max) > 0) {            max = y;//y Greater        }        if (Z.compareto (max) > 0) {            max = Z;//now Z larger                   } return        max;//Return Max Object    } public    static void Main (String args[]) {
  SYSTEM.OUT.PRINTLN ("Result" + getmaxnuum (3, 4, 5));  Results 5        System.out.println ("result" + getmaxnuum (1.2, 6.6, 10.10)); Result 10.10   }}

We can also change the definition of the previous generic class:

public class Genericclassdemo<t extends number> {     private T t;       Public Genericclassdemo () {     } public    Genericclassdemo (T t) {         this.t = T;    }    public void sett (T t) {        this.t = t;    }    Public T Gett () {         return T;    }}

At this point in the instantiation of the Genericclassdemo generic class, the parameter type can only be a subclass of number and number. On this basis, let's look at an example of a generic method:

/** * When adding the upper and lower bounds limit in a generic method, it must be added at the time of the generic Declaration; * That is, add the upper and lower bounds on <T> between the permission modifier and the return value */public <t extends number> t Gett (genericlassdemo<t> demo) {    T t = dem O.gett ();    return t;}

Generic Array

In Java it is not possible to create an array of the exact generic type.

list<string>[] LSA = new arraylist<string>[10];  Not really allowed. Object o = LSA;    Object[] OA = (object[]) o;    list<integer> li = new arraylist<integer> ();    Li.add (New Integer (3));    Oa[1] = Li; Unsound, but passes run time store check    String s = lsa[1].get (0);//Run-time error:classcastexception.

In this case, because of the JVM generic erasure mechanism, the JVM is not aware of the generic information at runtime, so it is possible to assign a ArrayList to oa[1] without exception, but to do a type conversion when the data is fetched, So there will be classcastexception, if you can make the declaration of a generic array, the above-mentioned situation will not have any warnings and errors during the compilation period, only errors will occur at run time. Instead of restricting the declaration of a generic array, it is much better to have a type-safety problem with the code at compile time than to have no hint.

The following wildcard is allowed: the type of the array cannot be a type variable, unless it is in the form of a wildcard, because in the way of a wildcard, the final fetch of the data is to make an explicit type conversion.

list<?>[] LSA = new list<?>[10]; OK, array of unbounded wildcard type.    Object o = LSA;    Object[] OA = (object[]) o;    list<integer> li = new arraylist<integer> ();    Li.add (New Integer (3));    Oa[1] = Li; Correct.    Integer i = (integer) lsa[1].get (0); Ok

Related articles:

Differences between T and question marks (wildcard characters) in Java generics

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.