JKB-002 GENERICS IN JAVA 1.5 TUTORIAL

GENERICS IN JAVA 1.5 TUTORIAL

Collections are typeless in Java. For example, an ArrayList object can contain any Java object. Putting an object in a collection is easy.

ArrayList list = new ArrayList();
CustomerBean cb = new CustomerBean():

list.add(cb);

Getting an object from a collection requires a type cast.

cb = (CustomerBean) list.get(0);

There in lies the problem with typeless collections. If for some reason, the list contained an instance of a class other than CustomerBean, the get() operation will fail with a type cast exception.

ENTER GENERICS

In Java 1.5, the code above can be written as follows.

ArrayList<CustomerBean> list = new ArrayList<CustomerBean>();
CustomerBean cb = new CustomerBean():

list.add(cb);

Here, the compiler will ensure that only instances of the CustomerBean class (or subclass there of) are added to the list.

Getting an object from the collection does not require type casting.

cb = list.get(0);

The following is a compilation error.

String str = list.get(0); //Compiler will catch the error

ITERATION USING GENERIC COLLECTION

Easiest way to iterate over a collection is to use the new for syntax.

for (CustomerBean o : list) {
System.out.println(o.getName());
}

If you wish to use an Interator, it must also use generics.

Iterator<CustomerBean> iter = list.iterator();

while (iter.hasNext()) {
CustomerBean c = iter.next();
}

BYPASSING COMPILER CHECK

It’s not that hard to bypass the compiler checking for type correctness. Consider a method as follows.

public static void bypassGenericCheck(ArrayList l) {
l.add("Mama"); //Compiler gives warning not error
}

We call this method as follows.

ArrayList<CustomerBean> list = new ArrayList<CustomerBean>();
CustomerBean cb = new CustomerBean():

list.add(cb);
bypassGenericChec(list); //Add instances other than CustomerBean.

Iterator<CustomerBean> iter = list.iterator();

while (iter.hasNext()) {
CustomerBean c = iter.next(); //This line will fail with ClassCastException
}

In this case, compiler gives a mere warning for the add() call within the bypassGenericCheck() method. The line containing the iter.next() call will fail with ClassCastException when iter.next() returns a String.

CREATING CUSTOM COLLECTION TYPES

Certainly, generics can increase the amount of typing. One way to minimize typing is to create a custom collection class. For example, if our application has ArrayList<CustomerBean> appearing in many places, we may decide to develop a simple class as follows.

public class CustomerList extends ArrayList<CustomerBean> {
}

We can use it as follows.

CustomerList l = new CustomerList();

CustomerBean cb = new CustomerBean();
l.add(cb);