Advance Java

Learn New things from Rixosys

Generics Example Program

Generics Example Program in Java explaining how you use it effectively?

In this section we will explain you how you can use the Generics while writing the Java Program? The introduction to the Generics is the major step in the Java Language. Generics can be used to define the generic classes and methods thus bringing the generic types in the Java Programming Language.

There is lot of potential in the Generics to bring the improvements in the type safety and the maintainability of the large scale project. This tutorial will teach you how to add the Generics to the Java code in classes and the methods. Here we are also discussing about the detailed syntax of the Generics and explain its use in the Java code.

This tutorial is meant for the Advance and the intermediate programmers who want to learn the Generics in Java Programming Language. This tutorial also explains with the example code how to use the generics in classes, interfaces and the methods in the classes. I am assuming that the developers are familiar with the basics of the Java programming language and know how to declare classes and the interfaces.

You must have JDK 5 or above to run the program discussed here.

Now we will show you the examples of using the Generics in Java code.

Generic List Example

In this example I will show you how you can use the Generic Array List in your program. Here is the complete listing of the example program:

import java.util.*;
/** 
* @Author: Deepak Kumar
* Web: http://www.roseindia.net
*/
public class GenericsArrayList
{
	public static void main(String[] args) 
	{
		System.out.println("Simple use of Generics with ArrayList");
		List <String> list = new ArrayList<String>();
		list.add("One");
		list.add("Two");
		list.add("Three");
		list.add("Four");
		list.add("Five");
		list.add("Six");
		list.add("Seven");
		list.add("Eight");
		list.add("Nine");
		list.add("Ten");
		//Iterate through enhanced for loop
		for (String str : list) {
			System.out.println(str);
		}
	}
}

You can use the following code to create generic array:

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

Then we have added the data to the list and to iterate it we have used the Java enhanced loop:

	//Iterate through enhanced for loop
	for (String str : list) {
		System.out.println(str);
	}	

Generics Class Example

Now we will see how we can create the simple generic class using the Generics. In this example we will show you how to create a simple generic class which takes one generic parameter as constructor argument. In the Generics the type parameter should be followed by the class name and it should be between <> braces. The T is used as the generic type and it will be written like className <T>. Here is the code of the example program:

/*
 * @Author: Deepak Kumar
 * Web: http://www.roseindia.net
 *
 */
import java.lang.Integer;

public class SimpleGenericsClassExample {
 
    public static void main(String a[]){
         
        //Create class object with String type data
        SimpleDataHolder<String> strObject = new SimpleDataHolder<String>("RoseIndia.net");
        strObject.printObjectType();

        //Create class object with Boolean as type parameter
        SimpleDataHolder<Boolean> boolObject = new SimpleDataHolder<Boolean>(Boolean.TRUE);
        boolObject.printObjectType();


        //Create class object with Boolean as type parameter
        SimpleDataHolder<Integer> boolInt = new SimpleDataHolder<Integer>(new Integer(100));
        boolInt.printObjectType();

    }
}
 
/**
 * In this class T is a type parameter,
 * its type will be determined at the time 
 * of object creation. 
 */
class SimpleDataHolder<T>{
     
    //Declare Object
    private T content = null;
     
    //Constructor accepting one parameter
    public SimpleDataHolder(T param){
        this.content = param;
    }
     
    public T getObj(){
        return this.content;
    }
     
    //Print the type of Object
    public void printObjectType(){
        System.out.println("The Object type is : "+content.getClass().getName());
    }
}

In the above example we have declared a generic class SimpleDataHolder<T> and used it to create the object of different types as shown below:

        //Create class object with String type data
        SimpleDataHolder<String> strObject = new SimpleDataHolder<String>("RoseIndia.net");
        strObject.printObjectType();

        //Create class object with Boolean as type parameter
        SimpleDataHolder<Boolean> boolObject = new SimpleDataHolder<Boolean>(Boolean.TRUE);
        boolObject.printObjectType();


        //Create class object with Boolean as type parameter
        SimpleDataHolder<Integer> boolInt = new SimpleDataHolder<Integer>(new Integer(100));
        boolInt.printObjectType();

In the first example we have learned how to create generic class which takes one parameter as constructor argument of the class.

Run time Exceptions

Since we are not able to restrict a collection type (like ArrayList) to hold only a specific type (like Integer), there is a possibility that accidentally a different type may get stored. Code will be written in an assumption that, the collection container will have Integer. If a String is found at that place, we will get Run time exceptions.

package com.javapapers.java;

import java.util.ArrayList;

public class GenericsIntro {
	public static void main(String args[]) {

		ArrayList marksList = init();
		ArrayList resultList = add(marksList, 5);
	}

	public static ArrayList init() {
		ArrayList marksList = new ArrayList();
		marksList.add(new Integer(94));
		marksList.add(new String("Hundred"));
		marksList.add(new Integer(90));

		return marksList;
	}

	public static ArrayList add(ArrayList marksList, int increment) {

		ArrayList resultList = new ArrayList();
		for (Object mark : marksList) {
			int newMark = ((Integer) mark).intValue() + increment;
			resultList.add(new Integer(newMark));
		}
		return resultList;
	}
}

Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer at com.javapapers.java.GenericsIntro.add(GenericsIntro.java:25) at com.javapapers.java.GenericsIntro.main(GenericsIntro.java:9)

The above example program shows that we will not have any issues at compile time and when someone accidentally stores a type that is not intended and we will get a run time Java exception, ClassCastException.