Why Generics is introduced?



JDK 5.0 introduces several new extensions to the Java programming language, one of these is the introduction of Generics.
Why Generics is introduced?
Generics provides the abstraction over types. Here is a typical usage of that sort:
?
1
2
3
List l1 = new LinkedList(); // 1
l1.add(new Integer(10)); // 2
Integer x = (Integer) l1.iterator().next(); // 3
The cast on line 3 is slightly annoying. Typically, the programmer knows what kind of data has been placed into a particular list. However, the cast is essential. To ensure the assignment to a variable of type Integer is type safe, the cast is required.
Of course, the cast not only introduces clutter. It also introduces the possibility of a run time error, since the programmer may be mistaken.
What if programmers could mark a list as being restricted to contain a particular data type? This is the core idea behind generics.
Here is a example of the above given program using generics:
?
1
2
3
List <Integer> l1 = new LinkedList <Integer>(); // 1
l1.add(new Integer(10)); // 2
Integer x = l1.iterator().next(); // 3
Notice the type declaration for the variable l1. It specifies that this is not just an arbitrary List, but a List of Integer, written List<Integer>. We say that List is a generic interface that takes a type parameter–in this case, Integer. We also specify a type parameter when creating the list object.
Note, too, that the cast on line 3′ is gone.
What if there is no Generics?
The following block of Java code illustrates a problem that exists when not using generics. First, it declares an ArrayList of type Object. Then, it adds a String to the ArrayList. Finally, it attempts to retrieve the added String and cast it to an Integer.
?
1
2
3
List v = new ArrayList();
v.add("test");
Integer i = (Integer)v.get(0);        // Run time error
Although the code compiles without error, it throws a runtime exception (java.lang.ClassCastException)when executing the third line of code. This type of problem can be avoided by using generics and is the primary motivation for using generics.
When Generics is used?
Using generics, the above code fragment can be rewritten as follows:
?
1
2
3
List <String> v = new ArrayList <String>();
v.add("test");
Integer i = v.get(10); // (type error)  Compile time error
The type parameter String within the angle brackets declares the ArrayList to be constituted of String. With generics, it is no longer necessary to cast the third line to any particular type, because the result of v.get(10) is defined as String by the code generated by the compiler.
Summary
To sum up, the reasons to use Generics are as follows:
  • Stronger type checking at compile time.
  • Elimination of explicit cast.
  • Enabling better code reusability such as implementation of generic algorithms
Java Generic type is only a compile-time concept. During run-time, all types information is erased, and this is call Type Erasure.

No comments:

Post a Comment