Java generics in-depth explanation

Source: Internet
Author: User

The essence of a generic is a parameterized type, which means that the data type being manipulated is specified as a parameter.

Suppose we have a need to write a sorting method that can sort through an array of shapes, arrays of strings, and even any other type of array.

The answer is that you can use Java generics .

Using the concept of Java generics, we can write a generic method to sort an array of objects. The generic method is then called to sort an integer array, a floating-point array, an array of strings, and so on.

Generic methods

You can write a generic method that can receive different types of arguments when it is called. Depending on the type of argument passed to the generic method, the compiler handles each method call appropriately.

The following is the rule that defines a generic method:

    • All generic method declarations have a type parameter declaration part (delimited by angle brackets) that is part of the type parameter declaration before the method return type (<E> in the following example).
    • Each type parameter declaration section contains one or more type parameters, separated by commas between the parameters. A generic parameter, also known as a type variable, is the identifier used to specify a generic type name.
    • A type parameter can be used to declare a placeholder for the actual parameter type that returns a value type and can be obtained as a generic method.
    • The declaration of a generic method body is the same as other methods. Note that the type parameter can only represent a reference type, not the original type (like Int,double,char, and so on).
Instance

The following example shows how to print elements of different strings using a generic method:

Instance
 Public classgenericmethodtest{//generic method PrintArray    Public Static< E >voidPrintArray (e[] inputarray) {//Output array elements          for(E element:inputarray) {System.out.printf ('%s ', Element);    } System.out.println (); }      Public Static voidMain (String args[]) {//create arrays of different types: Integer, Double, and CharacterInteger[] Intarray = {1, 2, 3, 4, 5 }; Double[] Doublearray= {1.1, 2.2, 3.3, 4.4 }; Character[] Chararray= {' H ', ' E ', ' l ', ' l ', ' O ' }; System.out.println ("Integer array element is:" ); PrintArray (Intarray); //passing an array of integral typesSystem.out.println ("\ n the double array element is:" ); PrintArray (Doublearray); //passing a double-precision arraySystem.out.println ("\ n character array element is:" ); PrintArray (Chararray); //passing an array of character types    } }

Compile the above code and run the result as follows:

An integer array element is:12345 The array element of the double type is:1.12.23.34.4 character array element is  :  

Bounded type parameters:

There may be times when you want to limit the range of types that are allowed to pass 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. This is the purpose of the bounded type parameter.

To declare a bounded type parameter, first list the name of the type parameter, followed by the extends keyword, and then immediately following its upper bound.

Instance

The following example shows how "extends" is used in the general sense of meaning "extends" (class) or "Implements" (interface). The generic method in this example returns the maximum value of three comparable objects.

Instance
 Public classmaximumtest{//compare three values and return a maximum value    Public Static<textendsComparable<t>>t Maximum (t X, t y, t z) {T max= x;//Assuming X is the initial maximum value      if(Y.compareto (max) > 0) {Max= y;//Greater y      }      if(Z.compareto (max) > 0) {Max= Z;//now Z is bigger.      }      returnMax//returns the largest object   }    Public Static voidMain (String args[]) {System.out.printf ("%d,%d, and%d the largest number is%d\n\n",                   3, 4, 5, Maximum (3, 4, 5 ) ); System.out.printf ("The largest number of%.1f,%.1f and%.1f is%.1f\n\n",                   6.6, 8.8, 7.7, maximum (6.6, 8.8, 7.7 ) ); System.out.printf ("%s, the largest number in%s and%s is%s\n", "pear",         "Apple", "orange", Maximum ("pear", "apple", "orange" ) ); }}

Compile the above code and run the result as follows:

Thelargest number in 3,4, and 5 is 56.6, and the  largest number in 8.8 and 7.7 is 8.8pear, and the largest number of pear                
Generic class

The declaration of a generic class is similar to a declaration of a non-generic class except that the type parameter Declarations section is added after the class name.

As with generic methods, the type parameter declaration portion of a generic class also contains one or more type parameters, separated by commas. A generic parameter, also known as a type variable, is the identifier used to specify a generic type name. Because they accept one or more parameters, these classes are referred to as parameterized classes or parameterized types.

Instance

The following example demonstrates how we define a generic class:

Instance
 Public classBox<t> {     PrivateT T;  Public voidAdd (T t) { This. T =T; }    PublicT Get () {returnT; }    Public Static voidMain (string[] args) {Box<Integer> Integerbox =NewBox<integer>(); Box<String> Stringbox =NewBox<string>(); Integerbox.add (NewInteger (10)); Stringbox.add (NewString ("Rookie Tutorial")); System.out.printf ("Integer value:%d\n\n", Integerbox.get ()); System.out.printf ("String:%s\n", Stringbox.get ()); }}

Compile the above code and run the result as follows:

The integer value is  : The string is : Rookie tutorial   
Type wildcard character

1. Type wildcards are generally used instead of specific type parameters. For example, list<?> is logically a parent class for all list< concrete type arguments >, such as list<string>,list<integer> .

Instance
 Public classGenerictest { Public Static voidMain (string[] args) {List<String> name =NewArraylist<string>(); List<Integer> age =NewArraylist<integer>(); List<Number> number =NewArraylist<number>(); Name.add ("Icon"); Age.add (18); Number.add (314);        GetData (name);        GetData (age);          GetData (number); }     Public Static voidGetData (list<?>data) {System.out.println ("Data:" + data.get (0)); }}

The output is:

::£314   

parsing: Because the parameters of the GETDATE () method are of type list, Name,age,number can be used as an argument for this method, which is the function of the wildcard character.

2. The upper limit 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.

Instance
 Public classGenerictest { Public Static voidMain (string[] args) {List<String> name =NewArraylist<string>(); List<Integer> age =NewArraylist<integer>(); List<Number> number =NewArraylist<number>(); Name.add ("Icon"); Age.add (18); Number.add (314); //Getupernumber (name);//1Getupernumber (age);//2Getupernumber (number);//3          }     Public Static voidGetData (list<?>data) {System.out.println ("Data:" + data.get (0)); }       Public Static voidGetupernumber (list<?extendsNumber>data) {System.out.println ("Data:" + data.get (0)); }}

Output Result:

:£º314  

parsing: An error occurs at (//1) because the parameter in the Getupernumber () method has already qualified the parameter generic limit to number, so the generic string is not within this range, so it will be error-

3, the type of the wildcard lower limit through the shape as list<? Super Number> to define that a type can accept only number and its three-level parent class type, such as an instance of the Objec type.

<? Extends t> and <? The difference between Super t>

    • <? Extends t> indicates that the type represented by the wildcard is a subclass of type T.
    • <? Super t> indicates that the type represented by the wildcard is the parent class of type T.

Java generics in-depth explanation

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.