Java Generics Tutorial

Java Generics Tutorial List :

Introduction to Java Generics :

Generics is one of the most important feature of Java programming and it was introduced in Java 5.

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

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.


Advantage of Java Generics :

Type-safety and Compile-Time Checking

We can hold only a single type of objects in generics. It will not allow to store other objects.

In Java programming, at compile time, you expect to know if you pass a wrong type of parameter to a method. For instance, if you define

Dog dog = catreference ; // ERROR

where, catreference is a reference of type Cat, which is not related to Dog, In this case you will get a compilation error.

When Java was introduced, this was not carried through fully into the Collections library. So, for instance, you can write

ArrayList al = new ArrayList();
al.add("hello");
al.add(new Dog());

There is no control on what type of object you place into the ArrayList.We will not get any compilation errors. However, the program will not execute correctly.We will get the runtime error:

If you are using generics and if you want to add different object it will give compilation error.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(new Dog());//Compile Time Error

In the above code compiler will complain before running the code.


Type casting is not required :

There is no need to typecast the object in generics.

Before Generics, we need to type cast like :

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

After Generics, no need to typecast the object as shown in below code.

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

With Java's Generics features you can set the type of the collection to limit what kind of objects can be inserted into the collection. you don't have to cast the values you obtain from the collection.

Here is an example using Java's Generic's feature:

List<string> list = new ArrayList<string>();
list.add("String Value");
String string = list.get(0);

Iterating a Generic List :

You can iterate a generic List using an Iterator which is given below.

List<string> list = new ArrayList<string>;
Iterator<string> iterator = list.iterator();
while(iterator.hasNext()){
String string = iterator.next();
}

If you are using generics it is not required to cast the object returned from the iterator.next(). Because the compiler knows that it contains String instances. Therefore it is not necessary to cast the objects obtained from it.

You can also use the new for-loop, to iterate generic collection like:

List<string> list = new ArrayList<string>;
for(String string : list) {
System.out.println(string);
}

Generic List in Java :

In this example we have used ArrayList Class.

package com.example;

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

class GenericList {

	public static void main(String args[]) {

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

		list.add("Ravi");

		list.add("Raj");

		// 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());

		}

	}

}

Output

element is: Raj
Ravi
Raj

In Next Article we will discuss about Generics Map in java.




comments powered by Disqus