One largest() method for any comparable type, and a sum() that accepts a list of any kind of number.
Java · intermediate · 9 min · 39 steps · free
import java.util.List;
public class GenericMethodsDemo {
static <T extends Comparable<T>> T largest(List<T> items) {
T best = items.get(0);
for (T item : items) {
if (item.compareTo(best) > 0) {
best = item;
}
}
return best;
}
static double sum(List<? extends Number> nums) {
double total = 0;
for (Number n : nums) {
total += n.doubleValue();
}
return total;
}
public static void main(String[] args) {
int biggest = largest(List.of(3, 9, 4));
String lastWord = largest(List.of("kiwi", "apple"));
double s = sum(List.of(1, 2.5));
System.out.println(biggest + " " + lastWord + " " + s);
}
}best is created on the stack and points to a new Integer on the heap: 3.item is created and points to the same Integer as best. No copy is made.item goes out of scope and disappears.item is created on the stack and points to a new Integer on the heap: 9.item.compareTo(best) > 0 to decide which way the code goes.item is created on the stack and points to a new Integer on the heap: 4.item goes out of scope and disappears.for (T item : items).largest() has finished, so its variables are gone.biggest.best is created and refers to the text "kiwi". Because it is a literal, Java stores it once in the string pool.item is created and refers to the text "kiwi". Because it is a literal, Java stores it once in the string pool.item goes out of scope and disappears.item is created and refers to the text "apple". Because it is a literal, Java stores it once in the string pool.item goes out of scope and disappears.for (T item : items).largest() has finished, so its variables are gone.lastWord.total is created on the stack with the value 0.n is created on the stack and points to a new Integer on the heap: 1.total changes from 0 to 1. n goes out of scope and disappears.n is created on the stack and points to a new Double on the heap: 2.5.total changes from 1 to 3.5. n goes out of scope and disappears.for (Number n : nums).sum() has finished, so its variables are gone.s.9 kiwi 3.5.Answer: No: use List<? extends Number>. Generic types are not covariant.
Answer: So compareTo can be called on T. The bound promises compareTo exists.
← Generic Classes · Comparable and Comparator →