Commit e1e8b9e
committed
feat(generics): add generic Pair<K,V> class with demo in Main
WHAT:
- Implemented a generic class `Pair<K,V>` that stores a key-value pair.
- Added constructor for initialization and getter methods (`getKey()`, `getValue()`).
- Created `Main` class to demonstrate usage of `Pair<String,Integer>`.
- Printed keys and values to verify functionality.
WHY:
- To illustrate how generics allow type-safe and reusable classes in Java.
- Demonstrates how multiple type parameters (`K`, `V`) can represent different roles.
- Provides a custom example similar to `Map.Entry<K,V>` in Java Collections Framework.
HOW:
- Defined `class Pair<K,V>` with private fields `K key` and `V value`.
- Used type parameters instead of fixed types to ensure flexibility.
- In `Main`, instantiated `Pair<String,Integer>` objects for demonstration.
TYPE PARAMETER NAMING CONVENTIONS:
- By convention, single-letter type names are used:
- `T` → Type (general-purpose)
- `E` → Element (commonly used in collections)
- `K` → Key (commonly used in maps)
- `V` → Value (commonly used in maps)
- `N` → Number
- Example: `Map<K,V>` in Java
- `K` → type of keys
- `V` → type of values
REAL-WORLD USE CASES:
- **Maps/Key-Value Stores**: Represent entries like `HashMap.Entry<K,V>`.
- **Database Results**: Represent column-value pairs.
- **Configuration/Properties**: Store attribute-value mappings.
- **Networking**: Store headers or query parameters.
NOTES:
- Enhancements could include `toString()`, `equals()`, and `hashCode()` for better debugging and collection support.
- This example builds the foundation for understanding advanced generic classes in Java.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent dd27336 commit e1e8b9e
1 file changed
+6
-5
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | | - | |
| 1 | + | |
| 2 | + | |
2 | 3 | | |
3 | | - | |
4 | | - | |
5 | | - | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
6 | 7 | | |
7 | 8 | | |
8 | 9 | | |
9 | 10 | | |
10 | 11 | | |
11 | 12 | | |
| 13 | + | |
12 | 14 | | |
13 | 15 | | |
14 | 16 | | |
15 | 17 | | |
16 | | - | |
| |||
0 commit comments