-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathGenericWriting.java
More file actions
49 lines (38 loc) · 1.14 KB
/
GenericWriting.java
File metadata and controls
49 lines (38 loc) · 1.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package generics;
import java.util.*;
import java.lang.reflect.*;
/**
* RUN:
* javac generics/GenericWriting.java && java generics.GenericWriting
* OUTPUT:
* [generics.Apple@1befab0]
* [generics.Apple@13c5982]
* [generics.Apple@1befab0, generics.Apple@1186fab]
* [generics.Apple@13c5982, generics.Apple@14b7453]
*/
public class GenericWriting {
static <T> void writeExact(List<T> list, T item) {
list.add(item);
}
static List<Apple> apples = new ArrayList<Apple>();
static List<Fruit> fruits = new ArrayList<Fruit>();
static void f1() {
writeExact(apples, new Apple());
writeExact(fruits, new Apple());
}
static <T> void writeWithWildcard(List<? super T> list, T item) {
list.add(item);
}
static void f2() {
writeWithWildcard(apples, new Apple());
writeWithWildcard(fruits, new Apple());
}
public static void main(String[] args) {
f1();
System.out.println(apples);
System.out.println(fruits);
f2();
System.out.println(apples);
System.out.println(fruits);
}
}