Commit dd27336
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
2 files changed
+9
-5
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
2 | 2 | | |
3 | 3 | | |
4 | 4 | | |
5 | | - | |
6 | | - | |
7 | | - | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
8 | 12 | | |
9 | | - | |
| 13 | + | |
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
22 | 22 | | |
23 | 23 | | |
24 | 24 | | |
25 | | - | |
| 25 | + | |
0 commit comments