×

java · level 3 · unit 1 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A brings its own type parameter.

A whole class does not need to be generic: one method can be. A generic method announces its type parameter in angle brackets before its return type: static <T> T lastOf(List<T> items).

When you call it, you never say what T is. Java looks at the list you pass in and works it out. This is . Pass a List<String> and a String comes back, with no casts.

Type parameters only accept class types, so a list of whole numbers is List<Integer>, never List<int>. Need two types? List them with commas: <K, V>.

import java.util.List;
public class Main {
    static <T> T lastOf(List<T> items) {
        return items.get(items.size() - 1);
    }
    public static void main(String[] args) {
        List<String> drinks = List.of("tea", "coffee", "cocoa");
        List<Integer> scores = List.of(12, 30, 18);
        String drink = lastOf(drinks);
        int score = lastOf(scores);
        System.out.println(drink + " " + (score + 2));
    }
}

List.of(...) builds a small list in one line. Later you will see why it cannot be changed.