Commit faa96bd
committed
docs(generics): explain covariance with
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]>? extends Number and restrictions on adding elements1 parent 54eb4dc commit faa96bd
File tree
1 file changed
+12
-0
lines changed- Section24JavaGenerics/src/CovarianceInGenerics
1 file changed
+12
-0
lines changedLines changed: 12 additions & 0 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
0 commit comments