Sub topic 2
Generic Interfaces
This chapter covers generic interfaces and methods, bounds, and how generic types relate to each other.
Generic Interfaces
An interface is a list of methods that a class promises to provide. A generic interface has a type parameter, just like a generic class does. A type parameter is a placeholder name for a type, such as T.
interface Container<T> {
T get();
}
class TextBox implements Container<String> {
public String get() { return "hello"; }
}TextBox fills in T with String. Its get() method must return a String.
Generic Methods
A generic method declares its own type parameter. The parameter goes before the return type, as in <T>. The compiler works out T from the arguments you pass, so you never have to write it yourself.
Restricting Types with Bounds
A bound limits which types can fill in T. Writing <T extends Comparable<T>> means "T must be a type that can be compared." Because of the bound, the method is allowed to call compareTo.
Combining Multiple Bounds
You can join bounds with &, as in <T extends Number & Comparable<T>>. If one of the bounds is a class, it must come first.
Here is one program that uses all of these ideas:
import java.util.List;
interface Container<T> {
T get();
}
class TextBox implements Container<String> {
public String get() { return "hello"; }
}
public class Demo {
static <T> T first(List<T> list) {
return list.get(0);
}
static <T extends Comparable<T>> T bigger(T a, T b) {
return a.compareTo(b) >= 0 ? a : b;
}
static <T extends Number & Comparable<T>> double doubleIt(T n) {
return n.doubleValue() * 2;
}
static void printAll(List<?> list) {
for (Object item : list) {
System.out.println(item);
}
}
public static void main(String[] args) {
System.out.println(new TextBox().get()); // hello
System.out.println(first(List.of("a", "b"))); // a
System.out.println(bigger(3, 9)); // 9
System.out.println(doubleIt(4)); // 8.0
printAll(List.of(1, 2, 3)); // 1 2 3
}
}Why List<Integer> Is Not a List<Number>
Integer is a kind of Number. Even so, List<Integer> is not a kind of List<Number>. This rule is called invariance. To see why the rule exists, suppose Java allowed the assignment:
import java.util.ArrayList;
import java.util.List;
public class Invariance {
public static void main(String[] args) {
List<Integer> ints = new ArrayList<>();
// List<Number> nums = ints; // compile error
// nums.add(2.5); // would put a Double into a list of Integers
System.out.println(ints);
}
}Unbounded Wildcards
The wildcard ? means "some type, I don't care which." The printAll(List<?> list) method in the program above accepts any list. You can read items from it as Object. You cannot add items to it, except null.
Exercise
Does List<String> work as the argument to printAll(List<?> list)? Does it work as the argument to a method that takes List<Object>?
Show answer
It works with List<?>, because the wildcard accepts a list of any type. It does not work with List<Object>, because generic types are invariant.