You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
|**Primary Use Case**| When you are **reading** items *from* a generic structure (it *produces* items for you). | When you are **writing** items *to* a generic structure (it *consumes* items from you). |
18
18
19
+
20
+
21
+
## Wildcards with upper bounds
22
+
23
+
This example shows using wildcard types with upper bounds to accept lists of
24
+
subclasses.
25
+
26
+
```java
27
+
abstractclassShape {
28
+
29
+
abstractvoiddraw();
30
+
}
31
+
32
+
classRectangleextendsShape {
33
+
34
+
@Override
35
+
voiddraw() {
36
+
IO.println("Drawing rectangle");
37
+
}
38
+
}
39
+
40
+
classCircleextendsShape {
41
+
42
+
@Override
43
+
voiddraw() {
44
+
IO.println("Drawing circle");
45
+
}
46
+
}
47
+
48
+
// Generic wildcard example
49
+
void main() {
50
+
51
+
List<Rectangle> shapes1 =newArrayList<>();
52
+
shapes1.add(newRectangle());
53
+
54
+
List<Circle> shapes2 =newArrayList<>();
55
+
shapes2.add(newCircle());
56
+
shapes2.add(newCircle());
57
+
58
+
drawShapes(shapes1);
59
+
drawShapes(shapes2);
60
+
}
61
+
62
+
void drawShapes(List<? extends Shape> lists) {
63
+
64
+
for (Shape s : lists) {
65
+
s.draw();
66
+
}
67
+
}
68
+
```
69
+
70
+
The `drawShapes` method uses a bounded wildcard `? extends Shape` to accept
71
+
lists of any type that extends `Shape`. This demonstrates covariance - the
72
+
method can accept `List<Rectangle>`, `List<Circle>`, or `List<Shape>`. The
73
+
wildcard makes the method more flexible than `List<Shape>` alone, which would
74
+
not accept lists of subtypes. This is useful for read-only operations where
75
+
you need to process elements polymorphically without adding new elements.
0 commit comments