Generic Methods, Bounds and Wildcards

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

What you'll learn

GenericMethodsDemo.java

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);
    }
}

Step by step

  1. largest(List.of(3, 9, 4)): T becomes Integer, which is Comparable.
  2. best is created on the stack and points to a new Integer on the heap: 3.
  3. item is created and points to the same Integer as best. No copy is made.
  4. item goes out of scope and disappears.
  5. The end of this block is reached.
  6. item is created on the stack and points to a new Integer on the heap: 9.
  7. Java checks item.compareTo(best) > 0 to decide which way the code goes.
  8. 9 is bigger than 3: best becomes 9.
  9. The end of this block is reached.
  10. item is created on the stack and points to a new Integer on the heap: 4.
  11. item goes out of scope and disappears.
  12. The end of this block is reached.
  13. Java moves to the next element of the loop: for (T item : items).
  14. largest() has finished, so its variables are gone.
  15. The value it returned, 9, is stored in biggest.
  16. The same method, now with Strings: "kiwi" comes after "apple".
  17. best is created and refers to the text "kiwi". Because it is a literal, Java stores it once in the string pool.
  18. item is created and refers to the text "kiwi". Because it is a literal, Java stores it once in the string pool.
  19. item goes out of scope and disappears.
  20. The end of this block is reached.
  21. item is created and refers to the text "apple". Because it is a literal, Java stores it once in the string pool.
  22. item goes out of scope and disappears.
  23. The end of this block is reached.
  24. Java moves to the next element of the loop: for (T item : items).
  25. largest() has finished, so its variables are gone.
  26. The value it returned, "kiwi", is stored in lastWord.
  27. ? extends Number accepts a List of Integers, Doubles, or a mix.
  28. total is created on the stack with the value 0.
  29. n is created on the stack and points to a new Integer on the heap: 1.
  30. total changes from 0 to 1. n goes out of scope and disappears.
  31. The end of this block is reached.
  32. n is created on the stack and points to a new Double on the heap: 2.5.
  33. total changes from 1 to 3.5. n goes out of scope and disappears.
  34. The end of this block is reached.
  35. Java moves to the next element of the loop: for (Number n : nums).
  36. sum() has finished, so its variables are gone.
  37. The value it returned, 3.5, is stored in s.
  38. It prints 9 kiwi 3.5.
  39. 9, kiwi and 3.5: one method per job, working across many types.

Common mistakes

Best practices

Key takeaways

Check yourself

Does List<Number> accept a List<Integer>?

Answer: No: use List<? extends Number>. Generic types are not covariant.

Why <T extends Comparable<T>> in largest?

Answer: So compareTo can be called on T. The bound promises compareTo exists.

·

More in Generics