New and Legacy Code Example @ Java Generics

Generics and collection works well with new features introduced in Java 5 like new for loop, autoboxing/unboxing and functions that accept variable number of arguments. The core idea behind generics is type safety. Lets explore it.

AbstractList, ArrayList, LinkedList and Vector class implement List interface and they store objects in them Following is the signature of add method:

Java Code:
add(Object o)
So we can store any object in our List. Review the code below:
Java Code:
ArrayList myArrayList = new ArrayList();
String []strArray= new String[10];
for(int i=0;i<10;i++){
   strArray[i] = "Element" + i;
   myArrayList.add(strArray[i]);
}
System.out.println((String)myArrayList.get(3));
We stored String objects in the array list and to retrieve an object, we had to type cast it. Only programmer knows which objects he has stored in the ArrayList, so he is responsible to type cast it in the required type. What if, he by mistake casts it into wrong type?
Java Code:
System.out.println((Integer)myArrayList.get(3));
Error:
Exception in thread "main" java.lang.ClassCastException: java.lang.String
To avoid such conditions, generics come into play. We can specify the type for a List so that list can only hold or store objects of that very type. Objects of some other types wont be stored into the list and no type casting is required then.
Java Code:
ArrayList<String> myArrayList = new ArrayList<String>();
myArrayList can not only store ‘String objects. Type safety is ensured and now programmer has better control over the array list.

The type is specified in angle brackets when we are declaring an instance of a class or interface. Without generics the type parameters are omitted, but one must explicitly cast whenever an element is extracted from the list.


Using Generics with legacy code

Generics are new in Java and now developers understand the importance of it and it is being used as required. Question arises, what about the legacy code? Consider an IT firm that is working on an application for 5 years, and they used Java 1.4 for development. They the plan to use 1.5 for development simply because it is better than 1.4. Are they supposed to convert the old code to 1.5 also? This is not practical as it required lot of efforts and time. We may use older code with generics but definitely there will be some warnings. Lets take an example:

Legacy code:

Java Code:
public interface University {
    public void setStudents(Collection c);
    public Collection getStrudents();
}
public class UniImpl implements University{
     
    private Collection students;
    public UniImpl(){
        students = new ArrayList();
    }
    public Collection getStudents() {
        return students;
    }

    public void setStudents(Collection c) {
        this.students = c;
    } 
}
We have an interface and its implementation. Thing to note is that we are using a collection without any type. Assume that this code was written using JDL 1.4. We have getter and setter methods for the collection.

Using Generics with New code:

Java Code:
public static void main(String[] args) {
        UniImpl obj = new UniImpl();
        Collection<String> c = new ArrayList<String>();
        c.add("Laiq");
        c.add("Farjad");
        c.add("Dave");
        c.add("Mike");
        c.add("Ken");
         
        obj.setStudents(c);
         
        c = obj.getStrudents();
         
        for(String str:c )
        {
            System.out.println("Student: " + str);
        } 
     }
Here we make object of legacy class called UniImpl. Then we make a collection of String type and added data to it. We then called setter method of UniImpl class and passed it a collection object of type String. There was no error or warning there. All is ok so far. Then we called the getter method in order to get the collection. We got a warning saying:

ArrayList is a raw type. References to generic type ArrayList<E> should be parameterized


Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email