2015-09-07 11:44:36 -06:00
|
|
|
// generics/GenericReading.java
|
2015-12-15 11:47:04 -08:00
|
|
|
// (c)2016 MindView LLC: see Copyright.txt
|
2015-11-15 15:51:35 -08:00
|
|
|
// We make no guarantees that this code is fit for any purpose.
|
2016-09-23 13:23:35 -06:00
|
|
|
// Visit http://OnJava8.com for more book information.
|
2015-06-15 17:47:35 -07:00
|
|
|
import java.util.*;
|
|
|
|
|
|
|
|
public class GenericReading {
|
2016-01-25 18:05:55 -08:00
|
|
|
static List<Apple> apples = Arrays.asList(new Apple());
|
|
|
|
static List<Fruit> fruit = Arrays.asList(new Fruit());
|
2015-06-15 17:47:35 -07:00
|
|
|
static <T> T readExact(List<T> list) {
|
|
|
|
return list.get(0);
|
|
|
|
}
|
|
|
|
// A static method adapts to each call:
|
|
|
|
static void f1() {
|
|
|
|
Apple a = readExact(apples);
|
|
|
|
Fruit f = readExact(fruit);
|
|
|
|
f = readExact(apples);
|
|
|
|
}
|
2016-01-25 18:05:55 -08:00
|
|
|
// If you have a class, its type is
|
2015-06-15 17:47:35 -07:00
|
|
|
// established when the class is instantiated:
|
|
|
|
static class Reader<T> {
|
|
|
|
T readExact(List<T> list) { return list.get(0); }
|
|
|
|
}
|
|
|
|
static void f2() {
|
|
|
|
Reader<Fruit> fruitReader = new Reader<>();
|
|
|
|
Fruit f = fruitReader.readExact(fruit);
|
2016-01-25 18:05:55 -08:00
|
|
|
//- Fruit a = fruitReader.readExact(apples);
|
|
|
|
// error: incompatible types: List<Apple>
|
|
|
|
// cannot be converted to List<Fruit>
|
2015-06-15 17:47:35 -07:00
|
|
|
}
|
|
|
|
static class CovariantReader<T> {
|
|
|
|
T readCovariant(List<? extends T> list) {
|
|
|
|
return list.get(0);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
static void f3() {
|
|
|
|
CovariantReader<Fruit> fruitReader =
|
|
|
|
new CovariantReader<>();
|
|
|
|
Fruit f = fruitReader.readCovariant(fruit);
|
|
|
|
Fruit a = fruitReader.readCovariant(apples);
|
|
|
|
}
|
|
|
|
public static void main(String[] args) {
|
|
|
|
f1(); f2(); f3();
|
|
|
|
}
|
2015-09-07 11:44:36 -06:00
|
|
|
}
|