The Java Generics programming is introduced in J2SE 5 to deal with type-safe objects. Before generics, we can store any type of objects in collection i.e. non-generic. Now generics, forces the java programmer to store specific type of objects.
« Previous
Advantage of Java Generics
There are mainly 3 advantages of generics. They are as follows:
- Type-safety: We can hold only a single type of objects in generics. It doesn’t allow to store other objects.
-
Type casting is not required:
There is no need to typecast the object.
Before Generics, we need to type cast After Generics, we don't need to typecast the object List list = new ArrayList();
list.add("hello");
String s = (String) list.get(0);//typecastingList<String> list = new ArrayList<String>();
list.add("hello");
String s = list.get(0);
- 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 list = new ArrayList();
list.add("hello");
list.add(32); //Compile Time Error
Syntax to use generic collection - ClassOrInterface <type>
Simple example to use Generics - ArrayList <string>
Full Example of Java Generics
Here, we are using the ArrayList class, but you can use any collection class such as ArrayList, LinkedList, HashSet, TreeSet, HashMap, Comparator etc. | Now we are going to use map elements using generics. Here, we need to pass key and value. Let us understand it by a simple example: |
import java.util.*; class Simple { public static void main(String args[]) { ArrayList<String> list=new ArrayList<String>(); list.add("rahul"); list.add("jai"); //list.add(32);//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()); } } } |
import java.util.*; class Test { public static void main(String args[]) { Map<Integer,String> map=new HashMap<Integer,String>(); map.put(1,"vijay"); map.put(4,"umesh"); map.put(2,"ankit"); //Now use Map.Entry for Set and Iterator Set<Map.Entry<Integer,String>> set=map.entrySet(); Iterator<Map.Entry<Integer,String>> itr=set.iterator(); while(itr.hasNext()) { Map.Entry e=itr.next();//no need to typecast System.out.println(e.getKey()+" "+e.getValue()); } } } |
Output:element is: jai rahul jai |
Output: 1 vijay 2 ankit 4 umesh |