Type parameters
- Eclipse: Oxygen
- Java: 1.8
As developers, we always strive to create reusable and flexible applications with different types of data. Therefore, by using generics, we can do that. But here there are also several types of parameters available, such as the element, the key value, the number, etc.
In the following example, Class Data has multiple type parameters. Data is provided using a parameterized constructor, and to retrieve the data we use the getter method.  By using multiple type’s generics, different types of data can be provided. Class Data is receiving data as a Key-value pair where a key is integer and value is String.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
class Data<K,V>{ private K key; private V value; public Data(K key, V value) { this.key = key; this.value = value; } public K getKey() { return key; } public V getValue() { return value; } @Override public String toString() { return "Data [key=" + key + ", value=" + value + "]"; } } public class App { public static void main(String[] args) { Data<Integer, String> data = new Data<Integer, String>(1, "Chaand"); System.out.println("Key: "+data.getKey()+" value: "+data.getValue()); } } |
Output
1 |
Key: 1 value: Chaand |
Note: It is not compulsory that only a generic class can hold a generic method
In the following example, method types of generics are created.
The display method is created with parameters at type Element and Number and value can be provided as arguments.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
class Data1<K,V>{ private K key; private V value; public Data1(K key, V value) { this.key = key; this.value = value; } public K getKey() { return key; } public V getValue() { return value; } @Override public String toString() { return "Data [key=" + key + ", value=" + value + "]"; } public <E, N> void display(E element, N number){ System.out.println("Element: "+element+ " Number: "+number); } } public class App { public static void main(String[] args) { Data1<Integer, String> data = new Data1<Integer, String>(1, "Chaand"); System.out.println("Key: "+data.getKey()+" value: "+data.getValue()); data.display("2.0", 25); } } |
Output:
1 2 3 |
Key: 1 value: Chaand Element: 2.0 Number: 25 |
Contributed by: Poonam Tomar