java · level 3 · unit 1 · lesson 2
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
One method, a fallback. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
import java.util.List;
public class Main {
static <T> T pick(List<T> items, int index, T fallback) {
if (index < items.size()) {
return items.get(index);
}
return fallback;
}
public static void main(String[] args) {
List<String> pets = List.of("cat", "dog");
System.out.println(pick(pets, 1, "none"));
System.out.println(pick(pets, 5, "none"));
}
}
your turn
Your turn. Count the votes.
Announce the type parameter on line 3, in the gap before int. Then on line 15, count another meal from the list, like curry.
output
press run to see what happens
fix it
The lap timer will not compile. Can you fix it?
output
press run to see what happens
- Java says
unexpected typeon line 7. Look at what sits inside the angle brackets. - Type parameters only take class types, and
intis a plain value type. - Change
List<int>toList<Integer>on line 7, then run.
nailed it
one method now fits every type. :D
- A generic method puts
<T>before its return type. - Type inference works out
Tfrom the arguments. - Use
Integer, notint, inside angle brackets.
new words in your collection
- generic method
- type inference
This lesson isn’t saved. A free account remembers every lesson you finish.