Powered by Blogger.

What are Generics in Java

>> Saturday, March 28, 2015

In common term Generic means a common type of things or relating to a class or group of things not specific.

In Java Generics are introduced in 2004 within Java 5.0 features along with Enum, autoboxing and varargs , to provide compile time type-safety.Java Generic methods and generic classes enable programmers to specify, with a single method declaration, a set of related methods or, with a single class declaration, a set of related types, respectively.
What is type-safety?
It is just a check by compiler that correct Type(datatype) is used in correct place and there should not be any ClassCastException.
Some of the benifits of generics over non-generic code:
1. Stronger type checks at compile time:
A Java compiler applies strong type checking to generic code and issues errors if the code violates type safety. Fixing compile-time errors is easier than fixing runtime errors, which can be difficult to find.

2. Elimination of casts.
The following code snippet without generics requires casting:
List list = new ArrayList();
String s = (String) list.get(0);
When re-written to use generics, the code does not require casting:
List<string> list = new ArrayList<string>();
String s = list.get(0);   // no cast
3. Enabling programmers to implement generic algorithms.By using generics, programmers can implement generic algorithms that work on collections of different types, can be customized, and are type safe and easier to read.
Naming Conventions for Generics.
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
Reference Books:

Related Posts Plugin for WordPress, Blogger...
© javabynataraj.blogspot.com from 2009 - 2014. All rights reserved.