Learnitweb

Generics in Java – An introduction

Generics is one of the most important features introduced in Java 5. Generics enables classes and interfaces to be parameters when defining classes, interfaces and methods.

What the above statement means is an interface or class may be declared to take one or more type parameters, which are written in angle brackets and should be supplied when you declare a variable belonging to the interface or class or when you create a new instance of a class. For example:

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

Here list is declared to contain String type elements. We use angle brackets (<>) to specify the type parameter.

Advantages of Java Generics

Type checking at compile time

Without Generics, we can store any type of objects in a list. But with Generics, only declared type of elements could be added to a list. For example:

//Without Generics, both Integer and String type elements could be added to list
List list = new ArrayList();
list.add(100);
list.add("hello");

//With Generics, only declared type of elements could be added 
List<Integer> list = new ArrayList<Integer>();
list.add(100); 
list.add("hello");  // compile error

Fixing compile-time errors is easier than fixing run time errors. Generics helps in type safety as with Generics, list can now have only Integer type elements.

Type casting is not required

Since we define the class or interface to take one or more types, we don’t need to cast the elements while using generics. For example:

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

When re-written with generics, the code does not require casting:

List<String> list = new ArrayList<String>();
list.add("hello");
String s = list.get(0);   // no casting required

Generics helps implementing generic algorithms

Generics helps in implementing generic algorithms that work on collections of different types, and are type safe. Such algorithms are easier to customize, easier to read.