Commit fee6c53
committed
feat(generics): add example of upper-bounded wildcards with Number
WHAT:
- Implemented a `sum(List<? extends Number> numbers)` method that demonstrates
the use of **upper-bounded wildcards** in generics.
- Showed how a single method can handle lists of different numeric types
(`Integer`, `Double`, etc.) by leveraging `? extends Number`.
WHY:
- Upper-bounded wildcards (`? extends T`) allow flexibility in reading values from
collections while maintaining type safety.
- Ensures the method can work with any subtype of `Number` without overloading.
DETAILS:
- Iterates through a generic list of numbers and calculates the total sum by
converting each element to `doubleValue()`.
- Demonstrated usage with:
- `List<Integer>` → produces `6.0`
- `List<Double>` → produces `6.6`
BENEFITS:
- Promotes code reuse by writing one method that works for multiple numeric types.
- Avoids duplication and unnecessary overloads.
- Ensures compile-time type safety (prevents adding non-numeric types).
REAL-WORLD CONTEXT:
- Useful in math utilities, statistics calculators, or APIs dealing with mixed
numeric types.
- Builds foundation for understanding the difference between `? extends T`
(safe for reading) and `? super T` (safe for writing).
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent b63859a commit fee6c53
1 file changed
+31
-0
lines changedLines changed: 31 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 | + | |
| 13 | + | |
| 14 | + | |
| 15 | + | |
| 16 | + | |
| 17 | + | |
| 18 | + | |
| 19 | + | |
| 20 | + | |
| 21 | + | |
| 22 | + | |
| 23 | + | |
| 24 | + | |
| 25 | + | |
| 26 | + | |
| 27 | + | |
| 28 | + | |
| 29 | + | |
| 30 | + | |
| 31 | + | |
0 commit comments