Generics provide type safety to to the Java programming. Generics were first introduced in Java5.0. Before Generics a typical list handling program in Java used to be:
//Make a new list
List nameList = new ArrayList();
//Now add a string object to the list. Note that we can put any type of object in the list
nameList.add(new String("bubba");
//While fetching we have to know beforehand that the object returned is of type String otherwise
//it will throw an exception
String name = (String)nameList.iterator().next();
With generics the change in the code is as follows:
//Make a new list. Notice the change
List<String> nameList = new ArrayList<String>();
//Now add a string object to the list. Now we can put only objects of type String or its subtype
nameList.add(new String("bubba");
//Now we can safely fetch the object
String name = nameList.iterator().next();
Those coming from C++ background will find the generics resemblance to Templates. However there is one major difference. In C++ the templates types leads to generation of code for different types but the Java generics do not generate code for different types but handles it at runtime.
No comments:
Post a Comment