Answer: Java generics enable functions to be applied to multiple data types, improving code reusability. Details: Generic types are represented by angle brackets, such as
Java function generics improve code reusability
Generics in Java allow us to use them when defining functions or classes Type placeholder function. This allows us to create methods that work on multiple data types, thus increasing code reusability.
Understanding generics
Generic types are represented by angle brackets (<>), for example List<String>
represents a string List of types. We can use type variables to represent generic types, such as T
.
Create a generic function
To create a generic function, we specify the type variable when defining the function, for example:
public static <T> List<T> filterList(List<T> list, Predicate<T> predicate) { List<T> filteredList = new ArrayList<>(); for (T item : list) { if (predicate.test(item)) { filteredList.add(item); } } return filteredList; }
In this example , filterList()
The function uses the generic type T
to accept a list and a predicate (Predicate
). It returns a new list containing list items that satisfy the predicate condition.
Practical Case
Consider a scenario where elements that meet specific conditions need to be extracted from different types of lists. We can use the generic function filterList()
:
// 一个整数列表 List<Integer> numbers = List.of(1, 2, 3, 4, 5); // 筛选出大于 2 的整数 Predicate<Integer> predicate = i -> i > 2; List<Integer> filteredNumbers = filterList(numbers, predicate); // 一个字符串列表 List<String> colors = List.of("Red", "Green", "Blue", "Yellow"); // 筛选出以 "R" 开头的颜色 predicate = s -> s.startsWith("R"); List<String> filteredColors = filterList(colors, predicate);
By using the generic function filterList()
, we can easily perform filtering operations on different types of data , without writing duplicate code.
Advantages
Using function generics provides the following advantages:
The above is the detailed content of How does Java function generics improve code reusability?. For more information, please follow other related articles on the PHP Chinese website!