Powered by Blogger.

Uses of Generics in Java

The Java Generics features were added to the Java language from Java 5. Generics add stability to your code so that you can detect most of the bugs during compile time.

Benefits of generics over non-generic code:

1) Stronger type checks at compile time
Java compiler applies strong type checking to generic code creates error if the code violates type safety. So it is always easy to fix compile time errors than runtime errors. 

2) Eliminates type casts 
The following code sneppet without generics requires type casting

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

When we rewrite the above to use generics, we no need to type cast:

List list = new ArrayList();
list.add("hello");
String string = list.get(0);   // no cast

3) Enable programmers to implement generic algorithms that work on collections of different types, can be customized, and are type safe.

Generic Types:
A generic type is a generic class or interface that is parameterized over types.

A simple Non-generic Class:
The problem with the following non-generic class is, there is no way to verify how the class is used during compile time.

NonGenericClazz.java:


A Generic Version of NonGenericClazz class:
The following is the way/technique to create generic version of non generic class:

GenericClazz.java:

Type variable can be any non-primitive type: any class type, any interface type, any array type or even any other type variable. The same way/technique can be used to create generic interfaces.

The most commonly used type parameter names are:
E - Element (used extensively by the Java Collections Framework)
K - Key
N - Number
T - Type
V - Value

Invoking and Instantiating Generic Type:
GenericClazzTest.java:

Output:
get Integer:10

Try: integerClazz.setT("a String"); will result in compilation error. This shows, if generic code violates type safety, it would result in error as shown below:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
The method setT(Integer) in the type GenericClazz is not applicable for the arguments (String)

Note:
Understand the terminologies used in Java Generics i) Type Parameter  ii) Type Argument

  • T in GenericClazz is a "type parameter"
  • Integer in GenericClazz is a "type argument"  




0 comments:

Post a Comment