Skip to content

Commit faa96bd

Browse files
committed
docs(generics): explain covariance with ? extends Number and restrictions on adding elements
WHAT: - Added example demonstrating covariance in generics: - `List<Integer>` and `List<Double>` can both be assigned to `List<? extends Number>`. - Showed that `List<? extends Number>` is **read-only** (safe for reading as `Number`). - Highlighted restriction: cannot add elements (except `null`) due to type-safety ambiguity. WHY: - Covariance (`? extends T`) allows flexibility in reading data from collections of different subtypes. - Prevents unsafe insertions (e.g., adding an `Integer` into a `List<Double>`). - Encourages safe usage of generics when the intent is **consumption (read-only access)**. REAL-WORLD APPLICATIONS: - Useful for APIs where data can come from multiple numeric sources (`Integer`, `Double`, `Float`) but only needs to be processed/read. - Example use cases: - Statistical utilities: sum, average, min, max functions. - Reporting/visualization tools where numeric input can be of different subtypes. - Reinforces the **PECS principle** (Producer Extends, Consumer Super): - `extends` → producer (read). - `super` → consumer (write). NOTES: - `List<Integer>` → valid assignment to `List<? extends Number>`. - `List<Double>` → valid assignment as well. - Adding elements restricted → only `null` insertion allowed. - Safe for iterating and reading values as `Number`. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent 54eb4dc commit faa96bd

File tree

1 file changed

+12
-0
lines changed

1 file changed

+12
-0
lines changed
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
Covariance allows a generic type to be assigned to another generic type with a broader bound.
2+
For example, a List<Integer> can be assigned to a List<? extends Number> but not the other way around.
3+
4+
List<? extends Number> numbers;
5+
numbers = List.of(1, 2, 3); // List of Integer is valid
6+
numbers = List.of(1.1, 2.2, 3.3); // List of Double is valid
7+
You can use the wildcard type <? extends Number> to access elements from the list but cannot add elements to
8+
the list, except null:
9+
10+
List<? extends Number> numbers = List.of(1, 2, 3);
11+
// numbers.add(4); // Error: You can't add elements, because it doesn't know the exact type
12+
numbers.add(null); // Valid: You can add null

0 commit comments

Comments
 (0)