Debian Codegraph @

checker/tests/nullness/generics/CollectionsAnnotations.java

raw
1 import org.checkerframework.checker.nullness.qual.*;
2
3 // This is how I propose the Collection interface be annotated:
4 interface Collection1<E extends @Nullable Object> {
5 public void add(E elt);
6 }
7
8 class PriorityQueue1<E extends @NonNull Object> implements Collection1<E> {
9 public void add(E elt) {
10 // just to dereference elt
11 elt.hashCode();
12 }
13 }
14
15 class PriorityQueue2<E extends @NonNull Object> implements Collection1<E> {
16 public void add(E elt) {
17 // just to dereference elt
18 elt.hashCode();
19 }
20 }
21
22 // This is how the Collection interface is currently annotated
23 interface Collection2<E extends @NonNull Object> {
24 public void add(E elt);
25 }
26
27 class PriorityQueue3<E extends @NonNull Object> implements Collection2<E> {
28 public void add(E elt) {
29 // just to dereference elt
30 elt.hashCode();
31 }
32 }
33
34 class Methods {
35 static void addNull1(Collection1 l) {
36 // Allowed, because upper bound of Collection1 is Nullable.
37 // :: warning: [unchecked] unchecked call to add(E) as a member of the raw type Collection1
38 l.add(null);
39 }
40
41 static void bad1() {
42 addNull1(new PriorityQueue1());
43 }
44
45 // If the types are parameterized (as they should be)
46 static <@Nullable E extends @Nullable Object> void addNull2(Collection1<E> l) {
47 l.add(null);
48 }
49
50 static void bad2() {
51 // :: error: (type.argument.type.incompatible)
52 addNull2(new PriorityQueue1<@NonNull Object>());
53 }
54
55 public static void main(String[] args) {
56 bad2();
57 }
58
59 static void bad3() {
60 // :: error: (type.argument.type.incompatible)
61 addNull2(new PriorityQueue2<@NonNull Object>());
62 }
63
64 // :: error: (type.argument.type.incompatible)
65 static <@Nullable E> void addNull3(Collection2<E> l) {
66 l.add(null);
67 }
68 }