Skip to content

Commit e1e8b9e

Browse files
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

File tree

1 file changed

+6
-5
lines changed

1 file changed

+6
-5
lines changed

Section24JavaGenerics/src/GenericClass/Type Parameter

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,17 @@
1-
Here, the Pair<K, V> class has two type parameters K and V, and you can specify the types when you create an instance of Pair.
1+
Here, the Pair<K, V> class has two type parameters K and V, and
2+
you can specify the types when you create an instance of Pair.
23

3-
Type Parameter Naming Conventions
4-
5-
While you can name type parameters anything, the convention is to use single letters that describe the purpose of the type parameter:
4+
Type Parameter Naming Conventions:
5+
While you can name type parameters anything, the convention is to use single letters that describe the
6+
purpose of the type parameter.
67

78
T: Type
89
E: Element (used in collections)
910
K: Key (used in maps)
1011
V: Value (used in maps)
1112
N: Number
13+
1214
For example, in the java.util.Map<K, V> interface:
1315

1416
K stands for the key type
1517
V stands for the value type.
16-

0 commit comments

Comments
 (0)