• September 5, 2014
  • Generics
  • Comments Off on Generics in java

Generics in java

Generics:

Generics is a way of implementing generic programming. Generic programming provides the facility like for a set of related methods, declare a single method that support any valid types. Generics are introduced in java 5. In java, generics are added because of Compile time type safety.

Let us understand with an example. We have an ArrayList of string type and add an integer type element. Before java 5 this code will compile and throw exception at the runtime which is worse. Generics provides the facility of compile time type safety i.e. compiler check that the correct types should be used at the correct places and no ClassCastException.

How generics work?

Generics work on the concept of “Type Erasure”. As we discussed above generics are used for compile time type safety i.e. they work at the compile time. At the compile time java compiler uses the Type Erasure feature to erase or remove the generics type code and convert the code without generics.

Main features of generics:

  1. 1. Compile time type safety.
  2. 2. Removing risk of ClassCastException at run time.
  3. 3. No casting.

 

Related Topics:

How to build java project using ant in eclipse?
JAXB marshalling – convert java object to xml example.
How to create pdf file in java using iText jar?
Generics class example.
OGNL in struts 2.
Hibernate One-to-One Mapping using xml.
Send inline image in email using JavaMail API.
Quartz 2 JobListener example.

 


Comments are closed.