Posts

Showing posts from December, 2008

Java Generics - Be careful with SubTypes

In Java versions before the Tiger (Java 5.0) a Collection as we know it, will only contain Objects . The compiler knows that any Object can be put in the collection. The inability of the compiler to identify the intent of the programmer to use a collection of a particular type probably caused a lot of time spent on debugging ClassCastExceptions . Hello and Welcome Generics Generics in Java 5.0 (and versions after) will allow you to define a type for a Collection. The use of generics is not limited for typing Collections but I will only touch on this subject because it brings me great joy to know that i can express during compile time that i want a certain type of Collection. It was really a pain to experience it during runtime, specially when you need to deploy an application. Before Java 5.0 Sample code for a Java Collection before Java 5.0 Here is a sample code on how a Collection is used before Java 5.0 1 List listFoo = new ArrayList() ; 2 listFoo.add(new Foo()); 3 Foo aFoo = (Foo)