What is Generics?

Generics are a built-in language feature that will make your software more reliable .The feature of Generics in Java allows Applications to create classes and objects that can operate on any defined types. Programmers can now make use of the Generics feature for a much better code. There is no need for un-necessary casting when dealing with Objects in a Collection.

Why we use generics?
Generics add stability to your code by making more of your bugs detectable at compile time.
Let's begin by designing a nongeneric class.

public class NonGenerics {

        public static void main(String[] args) {
                Map data = new HashMap();
                data.put("Key1", new Integer(100));
Take a closer look at the last line involving casting of object pulled out of the HashMap. There is no restriction from Map or HashMap on what type of object we add to this collection. The only requirement is – it should be an object i.e. we cannot add primitive to the collection unless it is wrapped in its respective object. Can you visualize problem with above approach?
User of the data from collection is expecting that the data should be of type Integer, but the creator of data is not having any such restriction. If the data added is of type other than Integer then there will be a ClassCastException. e.g. instead of Integer you add String to the collection, and end up in ClassCastException when you try to call any method of Integer. When do you come to know about this problem? It is at runtime, which is not correct. The solution is – use of generics. Let us change above code to use generics.
import java.util.HashMap;
import java.util.Map;

public class UseGenerics {

        public static void main(String[] args) {
                Map<String, Integer> data = new HashMap<String, Integer>();
                data.put("Key1", new Integer(100));
here we are restricting the kind of objects we can add to the collection .we fix that key should be String type only and value should be Integer type...If at all you try to add any other type of data then there is compile time error. This means that the compiled code is generated using the generics only.

People who read this post also read :


Post a Comment


Twitter Delicious Facebook Digg Stumbleupon Favorites More