Generics

Generics was added in Java 5 to provide compile-time type checking and removing risk of ClassCastException that was common while working with collection classes.

The whole collection framework was re-written to use generics for type-safety. 
Let’s see how generics help us using collection classes safely.

There are mainly 3 advantages of generics. They are as follows:

1)Type-safety: We can hold only a single type of objects in generics. It doesn’t allow to store other objects.

2)Type casting is not required: There is no need to typecast the object.

Before Generics, we need to type cast:
List list = new ArrayList();  
list.add("hello");  
String s = (String) list.get(0);//typecasting  

After Generics, we don't need to typecast the object:
List<String> list = new ArrayList<String>();  
list.add("hello");  
String s = list.get(0);  

3) Compile-Time Checking: It is checked at compile time so problem will not occur at runtime. The good programming strategy says it is far better to handle the problem at compile time than runtime.

List<String> list = new ArrayList<String>();  
list.add("hello");  
list.add(32);//Compile Time Error 

Here, we are using the ArrayList class, but you can use any collection class such as ArrayList, LinkedList, HashSet, TreeSet, HashMap, Comparator etc.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import java.util.*;

class GenericDemo {

 public static void main(String args[]) {

  ArrayList<String> list = new ArrayList<String>();

  list.add("Pune");
  list.add("Nagpur");

  // list.add(32);//this will give compile time error
  
  String s = list.get(1);// type casting is not required

  System.out.println("element is: " + s);

  Iterator<String> itr = list.iterator();

  while (itr.hasNext()) {
   System.out.println(itr.next());
  }
 }
}


<-- Previous || Next -->

No comments:

Post a Comment