OnJava8-Examples/generics/GenericReading.java

47 lines
1.4 KiB
Java
Raw Permalink Normal View History

2015-09-07 11:44:36 -06:00
// generics/GenericReading.java
// (c)2021 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 {
static List<Apple> apples =
Arrays.asList(new Apple());
2016-01-25 18:05:55 -08:00
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);
}
// A class type is established
// when the class is instantiated:
2015-06-15 17:47:35 -07:00
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
}