import java.util.*;
class Util {
// PRODUCES T → use extends
// Accepts List<Integer>, List<Number>, etc — reads but cannot add
public static double sum(List<? extends Number> nums) {
double total = 0;
for (Number n : nums) total += n.doubleValue();
return total;
}
// CONSUMES T → use super
// Accepts List<Integer>, List<Number>, List<Object> — adds but cannot safely read
public static void addInts(List<? super Integer> sink) {
sink.add(1);
sink.add(2);
sink.add(3);
}
public static void main(String[] args) {
List<Integer> ints = List.of(1, 2, 3);
List<Double> dbls = List.of(1.5, 2.5);
System.out.println(sum(ints)); // 6.0
System.out.println(sum(dbls)); // 4.0
List<Number> sink = new ArrayList<>();
addInts(sink);
System.out.println(sink); // [1, 2, 3]
}
}
Create a free account and build your private vault. Share publicly whenever you want.