Introduction
Generics were introduced in Java 5 and gave a lot of flexibility. Generics is available for all the collection types and makes creating ArrayList, HashMap, Set, etc., straightforward and strongly-typed. We can create our own generics classes too. We can simply define variables on the fly by doing so. It is easy to create a Generic class in Java. Many programming languages, like Python, Scala, etc., have a collection called Tuple, which Java doesn’t have. A Tuple is similar to HashMap in the sense that it stores elements as key-value pairs. Example:
JavaTuple<String, Integer> jtuple = new JavaTuple<String, Integer>("Marks", 75);
We have to custom create this class and the required constructor too! Let’s get into it. In my case above, I am using a constructor with <String, Integer>. We can use any combination needed, provided we create the key of type K and the value of type V.
Generics class Example
Let us see how to define the Generics class JavaTuple. Our variables of type K and V will be final variables. We will keep it simple with just a toString() method and two-argument constructor.
public class JavaTuple<K, V> { final K k; final V v; public JavaTuple(K key, V value) { k = key; v = value; } public String toString() { return String.format("KEY: '%s', VALUE: '%s'", k, v); } }
Note that we usually pass the data types like String, Integer, Float, etc., but in this case, we are using K & V. Let us now use this in our main class:
JavaTuple<String, Integer> jtuple = new JavaTuple<String, Integer>("Marks", 75); System.out.println(jtuple);
Note that our class extends only the Object class, so it has methods that the Object class provides. Let us try this with some other combination:
JavaTuple<Character, Integer> jtuple2 = new JavaTuple<Character, Integer>('A', 90); System.out.println(jtuple2); Similarly, we can create a key-value pair of any type. We already have HashMap for this, but all we wanted to show in this example was how Generics could be implemented.
Note that we can extend this to any number of arguments. For example:
JavaTuple<Character, Integer, Integer> jtuple2 = new JavaTuple<Character, Integer, Integer>('A', 90, 100);
Here we have Character, Integer, Integer. In this case, the class definition will be:
public class JavaTuple<K, V, Y> {
Conclusion
We have shown an example for generics by giving the example of a simple collection Tuple. We can define any data type if we create a Generic class to store values. To make it a proper Collection, we need to implement the Collection interface:
public class JavaTuple<K, V, Y> implements Collection<E>{
People are also reading:
- Java If-else
- Queue in Java
- How to declare, initialize and populate Java int arrays?
- Java Map
- Scanner in Java
- Java Switch
- How to Format Java String Output?
- Java Do While Loop
- While Loop in Java
- Java For Loop
Leave a Comment on this Post