Written by nitinpai on April 4th, 2007
Java 5 Generics – Changing for good
I had recently tried some programming in JDK 1.6 which falls in the league of Java 5. The Eclipse environment started behaving strange in someway which I had not expected. The code which was irritating me was the one which included a collection object
List list = new ArrayList(); list.add("someString");
The Eclipse IDE flashed a warning beneath the 2nd line of the code.
“Type safety: The method add(Object) belongs to the raw type List. References to generic type List<E> should be parameterized”
I had switched my project preferences to allow compilation of my code with the Java 5 runtime library. It was not before I came to know that it was the Java 5 generics in action. The moment I switched it back to Java 1.4 runtime the warning luckily disappeared.
Java 5 has removed the old technique of having you to cast the collection returned object to predefining the same collection of the type you want to cast. In the above example if I want to indeed include a String object in the List then it is but obvious that I would cast the returned object from the List to String as follows:
String s = (String)list.iterator().next();
To avoid this obvious nature of casting while using a collection Java 5 asks you to parameterize the template you would be using in the collection. So in Java 5 the code I was trying to accomplish would be as follows,
List<String> list = new ArrayList<String>(); list.add("someString"); //and while retrieving String s = list().iterator().next();
The above code would be much more familiar to C++ programmers who have used templates. In case of Java it would be the same as using templates. Java 5 Generics has much more features and lots of new concepts for a clutter free code while using collections.