Skip to content

Commit e48cdc1

Browse files
committed
docs(generics): add comprehensive guide on type parameters and wildcards
WHAT: - Added a complete markdown file explaining Java Generics in detail. - Covered generic classes, interfaces, and methods with code examples. - Introduced wildcards (`?`, `? extends T`, `? super T`) and their use cases. - Included ASCII hierarchy diagram for Repository<T>, Box<T>, and UtilityMethods. - Clarified type parameter naming conventions (T, E, K, V, N). DETAILS: - Explained **type safety**: compile-time validation prevents runtime ClassCastException. - Demonstrated **code reuse**: one generic class works for multiple data types. - Added **generic interface example** (Repository<T>) with concrete implementations. - Provided **generic class (Box<T>)** and usage with Integer/String. - Added **generic methods** with simple and bounded type parameters. - Documented **wildcard usage**: - `List<?>` → unbounded, read-only. - `List<? extends Number>` → upper bound, safe for reading (covariant). - `List<? super Integer>` → lower bound, safe for writing (contravariant). - Included **quick comparison table** for wildcards. - Summarized big-picture impact of generics in frameworks (Spring, Hibernate, Collections API). WHY: - To serve as a single reference point for Java Generics fundamentals. - Helps avoid common pitfalls (e.g., adding elements to `? extends T` collections). - Reinforces understanding of variance and type erasure in practical contexts. REAL-WORLD USE: - `Repository<T>` pattern for DAOs in Spring/Hibernate. - `Box<T>`-like wrappers for caching or transport objects. - Wildcards in APIs that must accept multiple related types while preserving type safety. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent 0c4ee7e commit e48cdc1

File tree

1 file changed

+173
-0
lines changed
  • Section24JavaGenerics/src/WildcardsInGenerics

1 file changed

+173
-0
lines changed
Lines changed: 173 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,173 @@
1+
detailed explanation of wildcards and type parameters:
2+
3+
4+
🚀 Java Generics: A Complete Guide
5+
6+
## 📦 Class & Interface Hierarchy
7+
8+
```text
9+
+-----------------------------+
10+
| interface Repository<T> |
11+
+-----------------------------+
12+
| + save(T entity) |
13+
| + findById(int id): T |
14+
| + findAll(): List<T> |
15+
+-----------------------------+
16+
17+
|
18+
+---------------+---------------+
19+
| |
20+
+-----------------------------+ +-----------------------------+
21+
| class UserRepository | | class ProductRepository |
22+
| implements Repository<User> | | implements Repository<Product> |
23+
+-----------------------------+ +-----------------------------+
24+
| + save(User user) | | + save(Product p) |
25+
| + findById(int id) | | + findById(int id) |
26+
+-----------------------------+ +-----------------------------+
27+
28+
29+
+----------------------+
30+
| class Box<T> |
31+
+----------------------+
32+
| - T item |
33+
| + getItem(): T |
34+
| + setItem(T) |
35+
+----------------------+
36+
37+
+-----------------------------------+
38+
| class UtilityMethods |
39+
+-----------------------------------+
40+
| <T> void print(T item) |
41+
| <T extends Comparable<T>> T max( |
42+
| T a, T b ) |
43+
+-----------------------------------+
44+
45+
```
46+
47+
📘 Legend:
48+
• T, K, V → type parameters (placeholders for actual types).
49+
• Arrows (▲) → implementation / usage of generic interface.
50+
• Replace T with real types like User, Product, Integer, etc.
51+
52+
53+
54+
📖 Theory: Why Java Generics?
55+
1.
56+
2. Type Safety
57+
• Errors are caught at compile time rather than runtime.
58+
• Example:
59+
60+
List<String> names = new ArrayList<>();
61+
names.add("Alice");
62+
names.add(42); // ❌ Compile-time error
63+
64+
2. Code Reuse
65+
• Write once, use for many types.
66+
• Same class can handle User, Product, or Integer without rewriting logic.
67+
68+
69+
70+
🏗️ Generic Classes & Interfaces
71+
72+
// Generic interface
73+
public interface Repository<T> {
74+
void save(T entity);
75+
T findById(int id);
76+
List<T> findAll();
77+
}
78+
79+
// Implementation with concrete type
80+
public class UserRepository implements Repository<User> {
81+
public void save(User user) { ... }
82+
public User findById(int id) { ... }
83+
public List<User> findAll() { ... }
84+
}
85+
86+
87+
88+
🎁 Generic Class Example
89+
90+
public class Box<T> {
91+
private T item;
92+
93+
public T getItem() { return item; }
94+
public void setItem(T item) { this.item = item; }
95+
}
96+
97+
// Usage
98+
Box<Integer> intBox = new Box<>();
99+
intBox.setItem(42);
100+
101+
Box<String> strBox = new Box<>();
102+
strBox.setItem("Hello");
103+
104+
• Box<Integer> → T becomes Integer
105+
• Box<String> → T becomes String
106+
107+
108+
109+
🛠️ Generic Methods
110+
111+
public class UtilityMethods {
112+
// Simple generic method
113+
public static <T> void print(T item) {
114+
System.out.println(item);
115+
}
116+
117+
// With bounded type parameter
118+
public static <T extends Comparable<T>> T max(T a, T b) {
119+
return (a.compareTo(b) > 0) ? a : b;
120+
}
121+
}
122+
123+
// Usage
124+
UtilityMethods.print("Generics are powerful!");
125+
Integer bigger = UtilityMethods.max(10, 20);
126+
127+
• <T> before method return type = declares a generic type parameter.
128+
• T extends Comparable<T> = T must be a type that implements Comparable.
129+
130+
131+
132+
🌀 Wildcards in Generics:
133+
134+
Wildcards (?) add flexibility when exact type parameters aren’t known.
135+
136+
1. Unbounded Wildcard ?
137+
List<?> items = new ArrayList<String>();
138+
Object obj = items.get(0); // ✅ Safe (read as Object)
139+
items.add("Hello"); // ❌ Not allowed (unknown type)
140+
141+
Use when you only need to read.
142+
143+
2. Upper-Bounded Wildcard ? extends Type
144+
145+
List<? extends Number> nums = new ArrayList<Integer>();
146+
Number n = nums.get(0); // ✅ Safe
147+
nums.add(3.14); // ❌ Not allowed
148+
149+
Use when you consume data (read as parent type).
150+
151+
3. Lower-Bounded Wildcard ? super Type
152+
153+
List<? super Integer> ints = new ArrayList<Number>();
154+
ints.add(42); // ✅ Safe (Integer is allowed)
155+
Object obj = ints.get(0); // ✅ But only read as Object
156+
157+
Use when you produce data (add elements safely).
158+
159+
160+
161+
🧩 Quick Comparisons:
162+
• List<?> → unknown type, read-only.
163+
• List<? extends Number> → safe to read as Number, not safe to add.
164+
• List<? super Integer> → safe to add Integer, not safe to read as Integer.
165+
166+
167+
168+
🌐 Big Picture
169+
170+
Generics in Java are like templates: they allow one blueprint to generate many type-safe variants of classes,
171+
interfaces, and methods.
172+
173+
They shine most in frameworks (Spring, Hibernate, Collections API) where flexibility meets type safety.

0 commit comments

Comments
 (0)