Skip to content

Commit dd27336

Browse files
committed
feat(generics): implement custom generic Pair<K,V> class with usage demo
WHAT: - Added a generic `Pair<K,V>` class that can hold a key-value pair of any types. - Type parameters: - `K` → Key - `V` → Value - Provides constructor and getter methods (`getKey()`, `getValue()`). - Created `Main` class to demonstrate usage of the `Pair` class. - Example with `Pair<String, Integer>` storing ("Age", 50) and ("Age", 88). - Printed keys and values to validate correctness. WHY: - Showcases how to define and use custom generic classes in Java. - Demonstrates type-safety and reusability compared to raw types. - Eliminates need for casting, reducing runtime errors. HOW: - Defined `class Pair<K,V>` with private fields `K key` and `V value`. - Provided constructor to initialize both fields. - Getter methods return strongly-typed key and value. - In `Main`, created multiple `Pair<String,Integer>` objects to simulate real-world key-value mapping. REAL-WORLD APPLICATIONS: - **Data Storage**: Represent entries similar to `Map.Entry<K,V>` in Java Collections. - **Configurations**: Store property-value or attribute-value pairs. - **Database Results**: Represent column-value pairs for rows. - **Networking**: Key-value headers or parameters in API requests. NOTES: - Java Collections Framework provides a built-in `Map.Entry<K,V>` interface that works like this `Pair`. - This example builds intuition for how generics power frameworks like `HashMap`, `ConcurrentHashMap`, etc. - Enhancements could include: - `setKey()` and `setValue()` methods for mutability. - Overriding `toString()`, `equals()`, and `hashCode()` for better usability in collections. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent faa96bd commit dd27336

File tree

2 files changed

+9
-5
lines changed

2 files changed

+9
-5
lines changed

Section24JavaGenerics/src/GenericClass/Main.java

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,12 @@
22

33
public class Main {
44
public static void main(String[] args) {
5-
Pair<String, Integer> pair = new Pair<>("Age", 30);
6-
System.out.println("Key: " + pair.getKey()); // Prints: Key: Age
7-
System.out.println("Value: " + pair.getValue()); // Prints: Value: 30
5+
Pair<String, Integer> pair = new Pair<>("Age", 50);
6+
Pair<String, Integer> pair2 = new Pair<>("Age", 88);
7+
8+
System.out.println("Key: " + pair.getKey());
9+
System.out.println("Key: " + pair2.getKey());
10+
System.out.println("Value: " + pair.getValue());
11+
System.out.println("Value: " + pair2.getValue());
812
}
9-
}
13+
}

Section24JavaGenerics/src/GenericClass/Pair.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,4 +22,4 @@ public V getValue() {
2222
Map<String, Integer> map = new HashMap<>();
2323
map.put("One", 1);
2424
map.put("Two", 2);
25-
*/
25+
*/

0 commit comments

Comments
 (0)