Generics in Java with examples


Generics has been introduced in java 1.5.Generics provide many advantage like code re-usability and detect compile time error related to type safety.

Idea is to pass object as an parameter to the class, function and interface(like passing object Integer,Double or any other user defined object).
Primitive types like int, double etc are not allowed to pass as an parameter.

Generic Class Illustration:

package com.devil.java.generics;

public class GenericClass<T> {
T genericObject;

public GenericClass(T obj) {
this.genericObject = obj;
}

public T getGenericObject() {
return genericObject;
}

}

For creating object for the above class:

When String is passed as an parameter:

GenericClass<String> stringObject = new GenericClass<String>(
"Merry Christmas");

When Integer is passed as an parameter:

GenericClass<Integer> intObject = new GenericClass<Integer>(10);

When Double is passed as an parameter:

GenericClass<Integer> intObject = new GenericClass<Integer>(80.89);

Now if we try to pass primitive type as an parameter,it will give compile error.Like below code will give compile error.

GenericClass<int> doubleObject = new GenericClass<int>(80);

Example illustrating above object (not primitive type)passing is:

package com.devil.java.generics;

public class GenericClassMain {

public static void main(String args[]) {
GenericClass<String> stringObject = new GenericClass<String>(
"Merry Christmas");
String str = stringObject.getGenericObject();
System.out.println("String name from Generic is: " + str);

GenericClass<Integer> intObject = new GenericClass<Integer>(10);

Integer intNumber = intObject.getGenericObject();
System.out.println("IntNumber from generic is :" + intNumber);

GenericClass<Double> doubleObject = new GenericClass<Double>(80.89);

Double doubleNumber = doubleObject.getGenericObject();
System.out.println("Double Number from generic is :" + doubleNumber);
}
}

Output of the above Programme will be:
String name from Generic is: Merry Christmas
IntNumber from generic is :10
Double Number from generic is :80.89

We can pass multiple type parameters as well like:

class name<T1, T2, …, Tn> { /* … */ }

Like in this example , we are passing three parameter.

package com.devil.java.generics;

public class GenericClassMultipleParameter<T, S, U> {
public T obj1;
public S obj2;
public U obj3;

public GenericClassMultipleParameter(T ob1, S ob2, U ob3) {
this.obj1 = ob1;
this.obj2 = ob2;
this.obj3 = ob3;
}

public void printParameter() {
System.out.println("First Parameter is: " + obj1);
System.out.println("Second Parameter is: " + obj2);
System.out.println("Third Parameter is: " + obj3);

}
}

Programme to use above class is :

package com.devil.java.generics;

public class GenericClassMultipleParameterMain {
public static void main(String args[]) {
GenericClassMultipleParameter<String, Integer, Double> genericObject =
new GenericClassMultipleParameter<String, Integer, Double>(
"Merry Christmas", 100, 900.67);
genericObject.printParameter();
}
}

Output of the above programme will be:

First Parameter is: Merry Christmas
Second Parameter is: 100
Third Parameter is: 900.67

Generic Function Illustration:

In the generic function we will use parameters between access modifier and return type like this:

For one parameter:

public <T> void printDetail(T object){/*....*/ }

For multiple parameters:

public <T,U,V> void printDetail(T object1,U object2,V object3){/*....*/}

Example illustrating using of one parameter:


package com.devil.java.generics;

public class GenericFuncton {

public <T> void printDetail(T object) {
System.out.println("Passed object is :" + object.getClass().getName()
+ " and value is :" + object);
}

public <T> T getObjectDetail(T object) {
return object;
}

public static void main(String args[]) {
GenericFuncton function = new GenericFuncton();
function.printDetail("Merry Christmas");
function.printDetail(800);
function.printDetail(456.90);

String str = function.getObjectDetail("Merry Christmas-2016");
System.out.println("Value of returned String object is: " + str);
/**similarly we can get do for other parameter */

}
}

Output of the above programme will be :

Passed object is :java.lang.String and value is :Merry Christmas
Passed object is :java.lang.Integer and value is :800
Passed object is :java.lang.Double and value is :456.9
Value of returned String object is: Merry Christmas-2016

Example illustrating using of multiple parameters:

package com.devil.java.generics;

package com.devil.java.generics;

public class GenericFunctonMultipleParameter {
public <T, U, V> void printDetail(T object1, T object2, T object3) {
System.out.println("First Passed object is :"
+ object1.getClass().getName() + " and value is :" + object1);

System.out.println("Second Passed object is :"
+ object2.getClass().getName() + " and value is :" + object2);

System.out.println("Third Passed object is :"
+ object1.getClass().getName() + " and value is :" + object3);
}

public static void main(String args[]) {
GenericFunctonMultipleParameter function =
new GenericFunctonMultipleParameter();
function.printDetail("Merry Christmas",800,456.90);

}
}

Output of the above programme will be :

First Passed object is :java.lang.String and value is :Merry Christmas
Second Passed object is :java.lang.Integer and value is :800
Third Passed object is :java.lang.String and value is :456.9

Advantage of using Java Generics:

1.Code re-usabilty:We can write a generic method/class/interface once and use for any type we want.

2.Using of generics will detect errors at compile rather than throwing error/exception at run time.like if we do not use generic collection (say ArrayList) in our example.It will allow insertion of 10 (Integer type) at compile time but will throw exception at run time.

package com.devil.java.generics;

import java.util.ArrayList;

public class NoTypeSafety {
public static void main(String[] args)
{
ArrayList al = new ArrayList();

al.add("Banglore");
al.add("Kolkata");
al.add(10); // Compiler allows this

String s1 = (String)al.get(0);
String s2 = (String)al.get(1);

// throws Runtime Exception
String s3 = (String)al.get(2);
}
}

Output will be :

Exception in thread “main” java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
    at com.devil.java.generics.NoTypeSafety.main(NoTypeSafety.java:18)

Using of generics will solve this problem and will detect error at compile time, like this:

package com.devil.java.generics;

import java.util.ArrayList;

public class TypeSafety {
public static void main(String[] args)
{
ArrayList <String> al = new ArrayList<String> ();

al.add("Banglore");
al.add("Kolkata");

//  Compiler doesn't allow this
al.add(10);

String s1 = (String)al.get(0);
String s2 = (String)al.get(1);
String s3 = (String)al.get(2);
}
}

Compiler error will be :
The method add(int, String) in the type ArrayList<String> is not applicable for the arguments (int)

 

 

So this is all about using of generics  in Java.Let me now if there is any questions.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s