Home >Java >javaTutorial >How does Java function generics improve code reusability?
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 8742468051c85b06f0a0af9e3e506b5c, where T represents a placeholder type. Specify the type variable when creating a generic function, such as 8742468051c85b06f0a0af9e3e506b5c List8742468051c85b06f0a0af9e3e506b5c filterList(List8742468051c85b06f0a0af9e3e506b5c, Predicate8742468051c85b06f0a0af9e3e506b5c). Generic functions can be used for different types of lists, such as filtering a list of integers for elements greater than 2 or filtering a list of strings for elements starting with "R". Advantages of generics include code reuse, flexibility, and type safety.
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 (a8093152e673feb7aba1828c43532094), for example Listf7e83be87db5cd2d9a8a0b8117b38cd4
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!