java · level 3 · unit 1 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A tells Java what your type can do.
Inside <T>, Java knows nothing about T, so it only lets you call methods every object has, like equals. To find the biggest item you need to compare them, and plain T has no compareTo. Writing x.compareTo(y) gives cannot find symbol.
A bound fixes this. means any type that can compare itself with its own kind. String, Integer and Double all implement Comparable, so they are allowed in, and inside the method compareTo is ready to use.
a.compareTo(b) answers with a number: negative when a comes first, zero when they match, positive when a comes after. Check the sign, never the exact value.
import java.util.List;
public class Main {
static <T extends Comparable<T>> T biggest(List<T> items) {
T best = items.get(0);
for (T item : items) {
if (item.compareTo(best) > 0) {
best = item;
}
}
return best;
}
public static void main(String[] args) {
System.out.println(biggest(List.of(18, 42, 7)));
System.out.println(biggest(List.of("kiwi", "apple", "mango")));
System.out.println(biggest(List.of(2.5, 9.75, 4.0)));
}
} Here extends means "is or implements", for classes and interfaces alike.
guess first
Which fruit is the smallest? Guess first.
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
import java.util.List;
public class Main {
static <T extends Comparable<T>> T smallest(List<T> items) {
T best = items.get(0);
for (T item : items) {
if (item.compareTo(best) < 0) {
best = item;
}
}
return best;
}
public static void main(String[] args) {
System.out.println(smallest(List.of("mango", "apple", "Zebra")));
}
}
your turn
Your turn. Find the high score.
Add the bound on line 3 so compareTo is allowed. Then fill line 13 with a few whole-number scores, separated by commas.
output
press run to see what happens
fix it
The cheapest price is the dearest one. Can you fix it?
output
press run to see what happens
- It shows the dearest price. Which line decides when
bestchanges? compareTois positive whenpricecomes afterbest, so line 6 keeps the bigger prices.- Change
> 0to< 0on line 6, then run.
nailed it
your generic code can compare things now. :D
<T extends Comparable<T>>lets in only types that can be ordered.- A bound unlocks that type's methods inside your code.
compareTois negative, zero or positive. Check the sign.
new words in your collection
- bound
- Comparable
This lesson isn’t saved. A free account remembers every lesson you finish.