Sunday, August 23, 2009

Type safe collections in J2SE5.0

Arrays in Java have always been type safe—an array declared as type String (Stringfl) can't accept Integers (or ints). or anything other than Strings. But before Java 5 there was no syntax for declaring a type safe collection.

To make an ArrayList of Strings, we use
ArrayList myList = new ArrayList();

Or, the polymorphic equivalent:
List myList = new ArrayList();

There was no syntax that let you specify that myList will take Strings and only Strings. And with no way to specify a type for the ArrayList, the compiler couldn't enforce that you put only things of the specified type into the list.

The Legacy Way to Do Collections

Here's a review of a pre-Java 5 ArrayList intended to hold Strings.
List myList = new ArrayList(); // can't declare a type
myList.add("Fred"); // OK. it will hold Strings
myList. add(new Customer()); // and it will hold other objects too
myList.add(new lnteger(42)); //and Integers....

A non-generic collection can hold any kind of object; it also holds anything that is NOT a primitive. And since a pre-Java 5 collection could hold anything, the methods that get objects out of the collection could have only one kind of return type—java.lang.Object. That meant that getting a String back out of our only-Strings-intended list required a cast:

String s = (String) myList.get(0);

And since you couldn't guarantee that what was coming out really was a String (since you were allowed to put anything in the list), the cast could fail at runtime.

Java 5 Generics

Java 5 generics takes care of both ends (the putting in and getting out) by enforcing the type of your collections. Let's update the String list:

List myList = new ArrayList();
myList.add("Fred"); // OK. it will hold Strings
myList.add(new Customer()); // compiler error!'.

By using generics syntax—which means putting the type in angle brackets , we're telling the compiler that this collection can hold only String objects. So, now that what you put IN is guaranteed, you can also guarantee what comes OUT, and that means you can gel rid of the cast when you get something from the collection. Instead of

String s = (String) myList.get(0); //pre-generics. when a String wasn't guaranteed
We can now just say
String s = myList.get(0);

Advantages of Generics
  • Type casting is automatic. The user can now get the object from a collection without bothering to type cast the object into the target class.
  • Since the validation of the types happen at compile time, run lime exceptions like Class cast exceptions are avoided.
Thanks
A.T.J

No comments:

Post a Comment