It will let you write methods that can act as general purpose helper methods for any type.
Here is an example of reversing the contents of a List
implementation and return it in an ArrayList
.
List<String> liststr = new ArrayList<>(List.of("A","B","C"));
List<String> reversed = reverse(liststr);
System.out.println(reversed);
List<Integer> listint = new ArrayList<>(List.of(1,2,3,4));
List<Integer> reverseint = reverse(listint);
System.out.println(reverseint);
And here is the method.
public static <T> List<T> reverse(ArrayList<T> list) {
List<T> rev = new ArrayList<>();
for (int i = list.size()-1; i >= 0; i--) {
rev.add(list.get(i));
}
return rev;
}
This could have been done a different way but it would require casting
of the return value and might also generate a runtime
cast exception
.
As in all generic methods and classes, type conflicts will be resolved at compile time
and not at runtime
.