Skip to content

Commit fee6c53

Browse files
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

File tree

1 file changed

+31
-0
lines changed
  • Section24JavaGenerics/src/UpperBoundedWildcards

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package UpperBoundedWildcards;
2+
3+
import java.util.List;
4+
5+
public class Main {
6+
public static double sum(List<? extends Number> numbers) {
7+
double total = 0.0;
8+
9+
for (Number number : numbers) {
10+
total += number.doubleValue();
11+
}
12+
return total;
13+
}
14+
15+
public static void main(String[] args) {
16+
List<Integer> intList = List.of(1, 2, 3);
17+
List<Double> doubleList = List.of(1.1, 2.2, 3.3);
18+
19+
System.out.println("Sum of integers: " + sum(intList));
20+
System.out.println("Sum of doubles: " + sum(doubleList));
21+
}
22+
}
23+
24+
/*
25+
Explanation:
26+
List<? extends Number> allows the sum method to accept a List of any type that extends Number, such as Integer, Double,
27+
Float, etc.
28+
The method can read elements from the list, but it cannot add elements to it
29+
(because it only knows that the elements are some subtype of Number, but it doesn't know the exact type).
30+
This flexibility is achieved using the upper-bounded wildcard ? extends Number.
31+
*/

0 commit comments

Comments
 (0)