Generics in Java 1.5Web Age Solutions Inc. IntroductionCollections 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(); 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 GenericsIn Java 1.5, the code above can be written as follows. ArrayList<CustomerBean> list = new ArrayList<CustomerBean>(); 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 CollectionEasiest way to iterate over a collection is to use the new for syntax. for (CustomerBean o : list) { If you wish to use an Interator, it must also use generics. Iterator<CustomerBean> iter = list.iterator(); Bypassing Compiler CheckIt's not that hard to bypass the compiler checking for type correctness. Consider a method as follows. public static void bypassGenericCheck(ArrayList l) { We call this method as follows. ArrayList<CustomerBean> list = new ArrayList<CustomerBean>(); Iterator<CustomerBean> iter = list.iterator(); 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 TypesCertainly, 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(); Feedback |