«Back to Home

Core Java

Topics

Generics In Java

Generics
 
In Java, generics were introduced in J2SE 5 to deal with the type-safe objects. Before generics, we can store any type of objects in the collection, which is non-generic. Now, generics force to store the specific type of objects in Java.
 
Advantage of Generics

Type-safety- Generics holds only a single type of object. It doesn’t allow storing other types of objects.
 
Type casting is not required- There is no need to typecast the object in generics.
 
For example, before generics, we need to type cast.
  1. ArrayList al = new ArrayList();  
  2. al.add("Java");  
  3. String s = (String) al.get(0); //typecasting  
Now, after generics, we don't need to typecast the object.
  1. ArrayList < String > al = new ArrayList < String > ();  
  2. al.add("Java");  
  3. String s = al.get(0);  
Compile-Time Checking- Generics checked at the compile time. Thus, problem will not occur at the runtime.
 
For example.
  1. ArrayList < String > al = new ArrayList < String > ();  
  2. al.add("Java");  
  3. al.add(7); //Compile Time Error  
Syntax

Class or Interface<Type>
 
Let’s see an example, given below, with ArrayList class.
 
Code
  1. import java.util.*;  
  2. public class GenericsExample {  
  3.     public static void main(String args[]) {  
  4.         ArrayList < String > al = new ArrayList < String > ();  
  5.         al.add("Bob");  
  6.         al.add("Jack");  
  7.         String s = al.get(1);  
  8.         System.out.println("Element : " + s);  
  9.         Iterator < String > i = al.iterator();  
  10.         while (i.hasNext()) {  
  11.             System.out.println(i.next());  
  12.         }  
  13.     }  
  14. }  
1

Output

2

In the example, shown above, we are using the ArrayList class, but we can use any collection class in generics and we can observe that there is no need of type casting.
 
Let’s see an example: with Map, given below.
 
Code
  1. import java.util.*;  
  2. public class GenericsExample {  
  3.     public static void main(String args[]) {  
  4.         Map < Integer, String > m = new HashMap < Integer, String > ();  
  5.         m.put(19"Bunny");  
  6.         m.put(45"Harry");  
  7.         m.put(63"Jack");  
  8.         Set < Map.Entry < Integer, String >> s = m.entrySet();  
  9.         Iterator < Map.Entry < Integer, String >> i = s.iterator();  
  10.         while (i.hasNext()) {  
  11.             Map.Entry e = i.next();  
  12.             System.out.println(e.getKey() + " " + e.getValue());  
  13.         }  
  14.     }  
  15. }  
3

Output

4

In the example, mentioned above, we use map elements, using generics. Now, we need to pass the key and value and we can observe that there is no need of type casting.
 
Generic class

A generic class can refer to any type. Now, we are using T type parameter to create the generic class of specific type.
 
Let’s see an example: Creating generic class
 
Code
  1. public class Gen < T > {  
  2.     T t;  
  3.     void add(T t) {  
  4.         this.t = t;  
  5.     }  
  6.     Tget() {  
  7.         return t;  
  8.     }  
  9. }  
5

The T type point to that it can refer to any type (like String, Integer, Student etc.). The type we specify for the class and it will be used to store and retrieve the data.
 
Let’s see the program to use the generic class.
 
Code
  1. public class GenericsExample {  
  2.     public static void main(String args[]) {  
  3.         Gen < Integer > m = new Gen < Integer > ();  
  4.         m.add(25269);  
  5.         System.out.println(m.get());  
  6.     }  
  7. }  
6

Output

7

Important type Parameters

T - Type
 
E - Element
 
K - Key
 
N - Number
 
V - Value
 
Generic Method

As same as generic class, we can create generic method that can accept any type of argument.
 
Let’s see an example.
 
Code
  1. public class GenericsExample {  
  2.     public static < E> void printArray(E[] elements) {  
  3.         for (E e : elements) {  
  4.             System.out.println(e);  
  5.         }  
  6.         System.out.println();  
  7.     }  
  8.     public static void main(String args[]) {  
  9.         Integer[] iArr = {123};  
  10.         Character[] cArr = {'H''A''R''R''Y'};  
  11.         System.out.println(" Int Array");  
  12.         printArray(iArr);  
  13.         System.out.println(" Char Array");  
  14.         printArray(cArr);  
  15.     }  
  16. }  
8
 
Output

9

In the above example, Generic method to print array elements and we are using E to denote the element.
 
Wildcard in Generics

The question mark (?) symbol signify wildcard element in generics that means any type. For example: If we write <? extends Number> it means any child class of Number like Integer, Float, double etc. Now, we can call the method of Number class by any child class object.
 
Let’s see an example.
 
Code
  1. import java.util.*;  
  2. abstract class Animal {  
  3.     abstract void eat();  
  4. }  
  5. class Dog extends Animal {  
  6.     void eat() {  
  7.         System.out.println("Dog eat non-veg..");  
  8.     }  
  9. }  
  10. class Cat extends Animal {  
  11.     void eat() {  
  12.         System.out.println("Cat eat veg..");  
  13.     }  
  14. }  
  15. public class GenericsExample {  
  16.     public static void animalEat(List << ? extends Animal > lists) {  
  17.         for (Animal a: lists) {  
  18.             a.eat();  
  19.         }  
  20.     }  
  21.     public static void main(String args[]) {  
  22.         List < Dog > al = new ArrayList < Dog > ();  
  23.         al.add(new Dog());  
  24.         List < Cat > al1 = new ArrayList < Cat > ();  
  25.         al1.add(new Cat());  
  26.         al1.add(new Cat());  
  27.         animalEat(al);  
  28.         animalEat(al1);  
  29.     }  
  30. }  
10
 
Output

11

Summary

Thus, we learned that Generics force to store the specific type of objects in Java and also learn its advantages in Java.