How to use Generics in java?

Generics can be used to create the collection with holding the objects of certain type. This eliminates the need of unnecessary casting of the object while retrieving from the collection.

Now lets look at the list containing integer objects :

List integerlist = new ArrayList();

integerlist .add(new Integer(777));

In this case if we try to add String to the integerlist , it will throw a syntax error.

// integerlist .add("I am a string ");

But at the same time if we try to add null then it is valid.

integerlist.add(null);

If we create collection from the objects of Class O then we can add the object of the class which extend the Class O to the collection.

For example :

List subclassesTest = new ArrayList();

subclassesTest.add(new Integer(777));
subclassesTest.add(new Float(777));

Here both Integer and Float are subclasses of Number therefore it is valid to add those objects to the array list.

Similarly we can add the type specific objects to the HashMap as follows :

Map multiTypeMap = new HashMap();

multiTypeMap.put(.5, "half");
multiTypeMap.put(7, "Seven");

In the above example we can see that we have added float and integer values in Number specific map.
Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment