Answer: Generic methods in Java allow code to be compatible with multiple types. Definition: Use angle brackets
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 staticvoid swap(T[] array, int i, int j) { T temp = array[i]; array[i] = array[j]; array[j] = temp; }
In this example,
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> 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 staticdouble 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> 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!