Skip to content

Commit 8e01b62

Browse files
committed
docs(generics): explain upper-bounded wildcards (? extends T) in Java
WHAT: - Added detailed documentation explaining the concept of **upper-bounded wildcards** in Java Generics. - Clarified syntax, purpose, and real-world usage scenarios. DETAILS: - Syntax: `<? extends SomeClass>` → type can be `SomeClass` or any subclass. - Example context: `List<? extends Number>` allows `Integer`, `Double`, `Float`, etc. - Focused on the *read-only* nature of collections with `? extends T` (safe for reading, not for adding new elements). - Explained how this pattern represents **covariance** in Java Generics. WHY: - Prevents code duplication by allowing methods to handle collections of multiple subtypes. - Ensures type safety when processing hierarchies (e.g., `Number` and its subclasses). - Ideal when you need to **consume** or **process** data but not **insert** into the collection. REAL-WORLD USE: - Processing lists of numeric values (e.g., `List<Integer>`, `List<Double>`) with a single utility method. - Useful in mathematical libraries, data aggregation, and reporting systems where inputs may vary but are all subtypes of a common parent class. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent fee6c53 commit 8e01b62

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
In Java Generics, an upper-bounded wildcard restricts the types that can be passed as arguments to a parameterized type.
2+
3+
We use the wildcard ? with an upper bound to indicate that the type can be any class that is a subclass of a specified
4+
class (including the class itself).
5+
6+
The syntax for upper-bounded wildcards is:
7+
8+
<? extends SomeClass>
9+
This means that the type parameter can be any type that is SomeClass or a subclass of SomeClass.
10+
11+
Why Use Upper-Bounded Wildcards?
12+
13+
Upper-bounded wildcards are useful when you want to read data from a generic structure but you don’t need to modify it
14+
(except in certain restricted ways).
15+
16+
This is sometimes referred to as “covariance.”
17+
18+
For example, if you have a method that processes a list of numbers,
19+
but it doesn’t need to add any new elements to the list, you can use an upper-bounded wildcard to
20+
allow the method to accept lists of Integer, Double, or any other subtype of Number.

0 commit comments

Comments
 (0)