Java Generics

This section contains details of Generics in Java. The Generics permits us to develop classes and objects that can work on any defined types.

Java Generics

Java Generics

The Generics permits us to develop classes and objects that can work on any defined types.

In general words, Generics allows us to create a single method for sorting that can be used  to sort Integer array, a String array or any type that supports ordering. Similarly, a generic class allows us to use this class for any defined types.

Generics permits us to catch the incompatible types during compilation. The main reason of using Generics code is to assures type safety. It means that types which are required for Application and the types which is sent by the client, must match. If there is difference or match is incompatible then it will leads to error. To ensure this match or compatibility we use Generics.

In Generics, classes and methods are defined with parametric type. You can replace a suitable java type during compilation with the help of these parametric type. This saves us from un-necessary type casting and also prevent us from using wrong or incompatible data types.

Before Generics

Map directory = new HashMap();
directory.put(new Long(9568575757L), "Sameer");
directory.put(new Long(9587654757L), "Joy");

Set dirValues = directory.entrySet();
Iterator dirIterator = dirValues.iterator();

while (dirIterator.hasNext())
{
Map.Entry anEntry = (Map.Entry)dirIterator.next();
Long number = (Long)anEntry.getKey(); 
String name = (String)anEntry.getValue(); 
System.out.println(number + ":" + name); 
}

After Generics

Map<Long, String> directory = new HashMap<Long, String>();
directory.put(new Long(9568575757L), "Sameer");
directory.put(new Long(9587654757L), "Joy");

Set<Map.Entry<Long, String>> dirValues = directory.entrySet();
Iterator<Map.Entry<Long, String>> dirIterator = dirValues.iterator();

while (dirIterator.hasNext())
{
Map.Entry<Long, String> anEntry = dirIterator.next();
Long number = anEntry.getKey();
String name = anEntry.getValue();
System.out.println(number + ":" + name); 
}

As you can see, we don't need to type cast in the above code. This is due to parametric type.

Given below the topics cover in this tutorial :