Applying generics in Java functions can achieve code reuse. The steps are as follows: Declare a generic type variable, such as
#How to apply generics in Java functions? Step analysis
Generics are a powerful tool in the Java language for specifying the type of a function or class when writing code. By using generics, you can create reusable code that works for multiple data types without having to write separate functions or classes for each type.
Steps to apply generics:
Declare a generic type variable: In a function, use angle brackets < > to declare one or more generic type variables. For example:
public <T> void printArray(T[] arr) { // ... }
Here, T
in angle brackets <> is a generic type variable.
Use generic types in functions: In the function body, use generic type variables as function parameters, return value types, or types of local variables. For example:
public <T> T max(T a, T b) { if (a.compareTo(b) > 0) { return a; } else { return b; } }
Specify generic type actual parameters: When you call a generic function, you need to specify generic type actual parameters. This will tell the compiler which actual type should be used. For example:
String[] arr = {"a", "b", "c"}; printArray(arr); // 泛型类型实参为 String
Practical case:
Let us create a generic function swap()
Swap two elements in the array Position of elements:
public <T> void swap(T[] arr, int i, int j) { T temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; }
Usage:
Integer[] arr = {1, 2, 3}; swap(arr, 0, 2); System.out.println(Arrays.toString(arr)); // 输出:[3, 2, 1]
The above is the detailed content of How to use generics in Java functions? Step analysis. For more information, please follow other related articles on the PHP Chinese website!