Chapter 4 · Robust, modern Java

Generics

You are reading the whole lesson on one page. Back to one step at a time

Step 1 of 21 · Concept

One class, any type

ArrayList<String> and ArrayList<Integer> are one class, ArrayList. Its authors wrote it once, for any type you put in the angle brackets. A class like that is generic.

In this lesson you will:

  • write generic classes and methods of your own,
  • limit which types they accept,
  • see why it is List<Integer> and not List<int>.
public class Main {
    public static void main(String[] args) {
        Box<String> word = new Box<>("hello");
        Box<Integer> number = new Box<>(42);
        System.out.println(word + " " + number);
        String w = word.get();
        int n = number.get();
        System.out.println(w.length() + n);
    }
}
public class Main {
    public static void main(String[] args) {
        Pair<String, Integer> p = new Pair<>("Ada", 36);
        Pair<Integer, String> q = p.swap();
        System.out.println(p);
        System.out.println(q);
        System.out.println(p.first().length() + q.first());
    }
}
import java.util.List;

public class Main {
    static <T> T first(List<T> list) {
        return list.get(0);
    }

    static <T extends Comparable<T>> T max(List<T> list) {
        T best = list.get(0);
        for (T item : list) {
            if (item.compareTo(best) > 0) {
                best = item;
            }
        }
        return best;
    }

    public static void main(String[] args) {
        List<String> names = List.of("Grace", "Ada", "Linus");
        List<Integer> numbers = List.of(3, 9, 4);
        System.out.println(first(names) + " " + first(numbers));
        System.out.println(max(names) + " " + max(numbers));
    }
}
import java.util.List;

public class Main {
    // write the method count here

    public static void main(String[] args) {
        List<String> letters = List.of("a", "b", "a", "c", "a");
        List<Integer> numbers = List.of(1, 2, 2, 3);
        int a = count(letters, "a");
        int two = count(numbers, 2);
        System.out.println("\"a\" appears " + a + " times");
        System.out.println("2 appears " + two + " times");
    }
}
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Integer> scores = new ArrayList<>();
        scores.add(90);
        scores.add(75);
        int sum = scores.get(0) + scores.get(1);
        System.out.println(sum);
        Integer a = 1000;
        Integer b = 1000;
        System.out.println(a == b);
        System.out.println(a.equals(b));
    }
}
public class Main {
    // largest: takes every item off the stack
    // and returns the largest one
    static <T> T largest(Stack<T> stack) {
        return null;
    }

    public static void main(String[] args) {
        Stack<String> words = new Stack<>();
        words.push("one");
        words.push("two");
        words.push("three");
        System.out.println(words.size() + " " + words.peek());
        System.out.println(words.pop() + " " + words.pop());
        boolean empty = words.isEmpty();
        System.out.println(words.size() + " " + empty);
        Stack<Integer> numbers = new Stack<>();
        numbers.push(4);
        numbers.push(11);
        numbers.push(7);
        Integer big = largest(numbers);
        System.out.println(big + " " + numbers.isEmpty());
    }
}
import java.util.List;

public class Sum {
    static double sum(List<Integer> list) {
        double total = 0;
        for (Integer n : list) {
            total += n;
        }
        return total;
    }

    public static void main(String[] args) {
        System.out.println(sum(List.of(1, 2, 3)));
        System.out.println(sum(List.of(1.5, 2.5)));
    }
}
Terminal
Step 1 of 7A generic class

Keyboard shortcuts

The step

ContinueEnter
Previous / next stepAlt+[ · Alt+]
Move along the steps bar← → Home End, then Enter
From a quiz's title to its answers↓
Skip to the stepTab, then Enter (first on the page)
Course outlineAlt+O
These shortcuts?

The workspace

Run the stepCtrl+Enter (⌘↵ on a Mac)
Lesson → editor → consoleF6 (Shift+F6 back)
Output ↔ TerminalCtrl+`
Focus the editorCtrl+. (⌘. on a Mac)
Hide or show the lessonAlt+L
Restore, close a messageEsc (outside the editor and the terminal)

The editor

Leave the editorF6 (Shift+F6 back); or Ctrl+M (⌃⇧M on a Mac), then Tab moves the focus (not in the vim mode)
Open a file by nameCtrl+P (⌘P on a Mac)
All commandsCtrl+Shift+P (⌘⇧P on a Mac) or F1
Go to a lineCtrl+G (⌃G on a Mac)
Show or hide the filesCtrl+B (⌘B on a Mac)
Previous / next file tabCtrl+Shift+[ · Ctrl+Shift+] (⌘⇧[ · ⌘⇧] on a Mac)
The file tabs← → Home End on a tab; Delete closes it
Save the files nowCtrl+S (⌘S on a Mac)
Go to a symbol in the fileCtrl+Shift+O (⌘⇧O on a Mac)
Go to the definitionF12
Format the fileCtrl+Shift+F (⌘⇧F on a Mac), or Shift+Alt+F
Go back / forward after a jumpAlt+← · Alt+→ (⌃- · ⌃⇧- on a Mac)