import java.util.*;
class Util {
// Generic method — type inferred from the argument
public static <T> T firstOrNull(List<T> items) {
return items.isEmpty() ? null : items.get(0);
}
// Bounded — T must be Comparable to itself
public static <T extends Comparable<T>> T max(List<T> items) {
T best = items.get(0);
for (T x : items) if (x.compareTo(best) > 0) best = x;
return best;
}
// Multiple bounds with &
public static <T extends Number & Comparable<T>> T maxNumber(List<T> nums) {
return max(nums);
}
public static void main(String[] args) {
System.out.println(firstOrNull(List.of("a", "b", "c"))); // a
System.out.println(max(List.of(3, 1, 4, 1, 5))); // 5
System.out.println(max(List.of("apple", "banana", "cherry"))); // cherry
}
}
Create a free account and build your private vault. Share publicly whenever you want.