Thursday, May 19, 2011

Generic Lists in java

By default you can put any Object into a List, but from Java 5, Java Generics makes it possible to limit the types of object you can insert into a List. Here is an example:

List<MyClass> list = new ArrayList<MyClass>();

This List can now only have MyObject instances inserted into it. You can then access and iterate its elements without casting them. Here is how it looks:

MyClass myObject = list.get(0);

for(MyClass anObject : list){
//do someting to anObject...

However, note that this support for custom classes and generics is compile time only. Because if you try to add object of AnyOtherClass to MyClass, it will throw compile time error. At runtime, JVM doesn't make any difference between List of Strings or List of Integer or List of MyClass.

No comments:

Post a Comment