java · level 3 · unit 1 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A class leaves a gap where the type goes.
You have used ArrayList<String> and HashMap<String, Integer>. Those angle brackets are generics at work. Someone wrote the list class once, with a gap for the type. You fill the gap each time you make one, and Java checks every item against it.
Write your own with a in angle brackets: static class Box<T>. Inside the class, T stands for whatever type the user picks. A Box<String> holds text, a Box<Integer> holds numbers, and one piece of code serves both.
The <> saves typing when you build one: new Box<>("tea") copies the type from the left side. Put the wrong type in and the program never compiles, so the mistake cannot reach your users.
public class Main {
static class Box<T> {
private T item;
Box(T item) {
this.item = item;
}
T open() {
return item;
}
}
public static void main(String[] args) {
Box<String> lunch = new Box<>("cheese sandwich");
Box<Integer> locker = new Box<>(42);
String food = lunch.open();
int number = locker.open();
System.out.println(food.toUpperCase());
System.out.println(number + 1);
}
} By habit a type parameter is one capital letter: T for type, E for element, K and V for key and value.
guess first
Same class, two types. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
public class Main {
static class Box<T> {
private T item;
Box(T item) {
this.item = item;
}
T open() {
return item;
}
}
public static void main(String[] args) {
Box<Integer> score = new Box<>(7);
Box<String> name = new Box<>("Priya");
System.out.println(name.open() + score.open() * 2);
}
}
your turn
Your turn. Build a box with two gaps.
A class can take two type parameters. On line 17, choose the type of the second one and give the Pair a matching value, like Integer and 12.
output
press run to see what happens
fix it
The box forgot its gap. Can you fix it?
output
press run to see what happens
- Java cannot find a symbol called
T. Where shouldTbe announced? - A type parameter is announced in angle brackets straight after the class name.
- Change line 2 to
static class Box<T> {, then run.
nailed it
your classes now work with any type. :D
- A type parameter like
Tis a gap for a type. - The diamond
<>lets Java copy the type for you. - Wrong types are caught before the program ever runs.
new words in your collection
- generic
- type parameter
- diamond
This lesson isn’t saved. A free account remembers every lesson you finish.