Java Generics
The essence of generics is a parameterized type, which means that the data type being operated on is specified as a parameter.
Suppose we have such a requirement: write a sorting method that can sort integer arrays, string arrays or even any other type of array. How to implement it?
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. Then, call this generic method to sort an array of integers, arrays of floats, arrays of strings, etc.
Generic method
You can write a generic method that can receive different types of parameters when called. Depending on the parameter types passed to the generic method, the compiler handles each method call appropriately.
The following are the rules for defining generic methods:
All generic method declarations have a type parameter declaration section (separated by angle brackets) that declares the type parameters section before the method return type (<E> in the example below).
Each type parameter declaration part contains one or more type parameters, separated by commas. A generic parameter, also called a type variable, is an identifier that specifies the name of a generic type.
Type parameters can be used to declare return value types and can serve as placeholders for the actual parameter types obtained by generic methods.
The declaration of a generic method body is the same as for other methods. Note that type parameters can only represent reference types, not primitive types (such as int, double, char, etc.).
Example
The following example demonstrates how to use generic methods to print elements of different strings:
public class GenericMethodTest { // 泛型方法 printArray public static < E > void printArray( E[] inputArray ) { // 输出数组元素 for ( E element : inputArray ){ System.out.printf( "%s ", element ); } System.out.println(); } public static void main( String args[] ) { // 创建不同类型数组: Integer, Double 和 Character Integer[] 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( "整型数组元素为:" ); printArray( intArray ); // 传递一个整型数组 System.out.println( "\n双精度型数组元素为:" ); printArray( doubleArray ); // 传递一个双精度型数组 System.out.println( "\n字符型数组元素为:" ); printArray( charArray ); // 传递一个字符型数组 } }
Compile the above code and the running results are as follows Shown:
整型数组元素为: 1 2 3 4 5 双精度型数组元素为: 1.1 2.2 3.3 4.4 字符型数组元素为: H E L L O
Bounded type parameters:
There may be times when you 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 wish to accept instances of Number or a subclass of Number. That's the purpose of bounded type parameters.
To declare a bounded type parameter, first list the name of the type parameter, followed by the extends keyword, and finally followed by its upper bound.
Example
The following example demonstrates how "extends" is used in the general sense to mean "extends" (class) or "implements" (interface). The generic method in this example returns the maximum value of three comparable objects.
public class MaximumTest { // 比较三个值并返回最大值 public static <T extends Comparable<T>> T maximum(T x, T y, T z) { T max = x; // 假设x是初始最大值 if ( y.compareTo( max ) > 0 ){ max = y; //y 更大 } if ( z.compareTo( max ) > 0 ){ max = z; // 现在 z 更大 } return max; // 返回最大对象 } public static void main( String args[] ) { System.out.printf( "%d, %d 和 %d 中最大的数为 %d\n\n", 3, 4, 5, maximum( 3, 4, 5 ) ); System.out.printf( "%.1f, %.1f 和 %.1f 中最大的数为 %.1f\n\n", 6.6, 8.8, 7.7, maximum( 6.6, 8.8, 7.7 ) ); System.out.printf( "%s, %s 和 %s 中最大的数为 %s\n","pear", "apple", "orange", maximum( "pear", "apple", "orange" ) ); } }
Compile the above code and the running results are as follows:
3, 4 和 5 中最大的数为 5 6.6, 8.8 和 7.7 中最大的数为 8.8 pear, apple 和 orange 中最大的数为 pear
Generic class
The declaration of a generic class is similar to the declaration of a non-generic class, except that a type parameter declaration part is added after the class name.
Like generic methods, the type parameter declaration part of a generic class also contains one or more type parameters, separated by commas. A generic parameter, also called a type variable, is an identifier that specifies the name of a generic type. Because they accept one or more parameters, these classes are called parameterized classes or parameterized types.
Example
The following example demonstrates how we define a generic class:
public class Box<T> { private T t; public void add(T t) { this.t = t; } public T get() { return t; } public static void main(String[] args) { Box<Integer> integerBox = new Box<Integer>(); Box<String> stringBox = new Box<String>(); integerBox.add(new Integer(10)); stringBox.add(new String("php中文网")); System.out.printf("整型值为 :%d\n\n", integerBox.get()); System.out.printf("字符串为 :%s\n", stringBox.get()); } }
Compile the above code, and the running result is as follows:
整型值为 :10 字符串为 :php中文网