Core Java - SPLessons

Java Generics

Chapter 36

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Java Generics

Java Generics

shape Description

Java Generics, While developing a collection , if one wants to store homogeneous element where the element type should be same as the element that are added to the collection then generics is used. Type casting is not required in generics. Developer can hold a single type of objects in generics.

Before generics, developer used to type cast as follows.

List list = new ArrayList();  
list.add("hello");  
String s = (String) list.get(0);//typecasting  

After Generics, don’t need to typecast the object.

List list = new ArrayList();  
list.add("hello");  
String s = list.get(0);  

shape Example

Java Generics, by using the ArrayList class following is an example, but one can use any collection class such as ArrayList, LinkedList, HashSet.

import java.util.ArrayList;
import java.util.Iterator;

public class generic {
	public static void main(String args[]){  
		ArrayList list=new ArrayList();  
		list.add("SPlesson");  
		list.add("Sam");  
		//list.add(32);//compile time error  
		  
		String s=list.get(1);//type casting is not required  
		System.out.println("An element is: "+s);  
		  
		Iterator itr=list.iterator();  
		while(itr.hasNext()){  
		System.out.println(itr.next());  
		}  
		}  
}

Output:
When compile the code result will be as follows.

An element is: Sam
SPlesson
Sam

To know more about arrays click here .

shape Generic class

The commonly type parameters are as follows:

T – Type
E – Element
K – Key
N – Number
V – Value
A class that can refer to any type is known as generic class. Following is an example using T type parameter to create the generic class of specific type.
MyGen.java

class MyGen{  
T obj;  
void add(T obj){this.obj=obj;}  
T get(){return obj;}  
}  

Where T type indicates that it can refer to any type like String, int.
generatorclass.java

public class generatorclass {
	public static void main(String args[]){  
		MyGen m=new MyGen();  
		m.add(4);  
		//m.add("splesson");//Compile time error  
		System.out.println(m.get());  
		}
}

Output
When compile the code following is the result will be displayed.

4

Generic Method

shape Description

The developer can create generic method that can accept any type of argument. Following is an example to print array of elements.
GenericMethod.java

public class GenericMethod {
	 public static  void printArray(E[] elements) {  
	        for ( E element : elements){          
	            System.out.println(element );  
	         }  
	         System.out.println();  
	    }  
	    public static void main( String args[] ) {  
	        Integer[] intArray = { 100, 200, 300 };  
	        Character[] charArray = { 'S', 'P', 'L', 'E', 'S','S','O','O','N','S' };  
	  
	        System.out.println( "Printing Integer Array" );  
	        printArray( intArray  );   
	  
	       System.out.println( "Printing Character Array" );  
	        printArray( charArray );   
	    }   
}

Here the developer used E to denote the element.

public static  void printArray(E[] elements) {  
	        for ( E element : elements)}

Output
When compile the code following is the result will be displayed. Where first integer array, second character array will be displayed.

Printing Integer Array
100
200
300

Printing Character Array
S
P
L
E
S
S
O
O
N
S

Difference between generics and collections

1)Its not a class or interface,so its unfair to compare it with interfaces,comparisons are done between two things that share some common properties.
2)is actually a concept with which you can restrict the type of element you want to add into collection.
There is not compile time check for the type of elements being added into collection.
3)While accessing the elements you need to write many typecasting code with if-else condition to process the data.This is a very big problem with java2 collections.
4)To resolve this problem Java vendor has added the concept of Generics in Java 5.

click here .

Summary

shape Key Points

  • Java Generics are utilized to create generic classes and generic methods.
  • No need to use type casting while working with Java Generics classes.