Answer: Generic methods in Java allow code to be compatible with multiple types. Definition: Use angle brackets <T> to specify type information for parameters and return values. Usage: Can be used to manipulate collections of different types and compare objects of different types. Restricted type parameters: Specify that the type is restricted to a certain type through the extends keyword. Practical combat: Generic methods are suitable for creating general sorting algorithms, such as quick sort.
Definition and usage skills of Java generic methods
Introduction
Pan Type methods allow you to write code that works on multiple types, thereby increasing code reusability and flexibility.
Define a generic method
To define a generic method, use angle brackets <> after the method name to specify the type parameters:
public static <T> void swap(T[] array, int i, int j) { T temp = array[i]; array[i] = array[j]; array[j] = temp; }
In this example, <T>
indicates that the type information of the method’s parameters and return value is unknown.
Use of generic methods
You can use generic methods to operate collections of different types:
Integer[] numbers = {1, 2, 3}; swap(numbers, 0, 2); // 交换数字 1 和 3
Similarly, you can also use generic methods To compare objects of different types:
public static <T extends Comparable<T>> int compare(T a, T b) { return a.compareTo(b); } int result = compare("Hello", "World"); // 比较字符串
Using Bounded type parameters
You can use the extends keyword to specify that a generic type parameter is bound to a certain type:
public static <T extends Number> double sum(T[] array) { double total = 0.0; for (T element : array) { total += element.doubleValue(); } return total; } double sum = sum(new Integer[]{1, 2, 3}); // 求整数和
Practical Case: Sorting Algorithm
Generic methods are very suitable for creating general sorting algorithms, such as quick sort:
public static <T extends Comparable<T>> void quickSort(T[] array) { // 略... } // 排序整数数组 int[] numbers = {2, 5, 1, 7, 3}; quickSort(numbers); // 排序字符串数组 String[] strings = {"Hello", "World", "Java"}; quickSort(strings);
The above is the detailed content of Definition and usage skills of Java generic methods. For more information, please follow other related articles on the PHP Chinese website!