View RSS Feed

My Java Tips

Java Generics with legacy code

Rate this Entry
by , 11-15-2011 at 06:31 PM (1109 Views)
In this post, I will write about how Java generics help us in using 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 requires a 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 (see the previous post). Thing to note is that we are using a collection without any type. Assume that this code was written using JDK 1.4. We have getter and setter methods for the collection.

New code:

Java Code:
public static void main(String[] args) {
		UniImpl obj = new UniImpl();
		Collection c = new ArrayList();


		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 should be parameterized

Compiler generated warning because it cannot guarantee its correctness. We are trying to get a collection of no type into a collection of type String. Compiler has no idea about the type of collection that getStudents method of UniImpl class will return.

Submit "Java Generics with legacy code" to Facebook Submit "Java Generics with legacy code" to Digg Submit "Java Generics with legacy code" to Submit "Java Generics with legacy code" to StumbleUpon Submit "Java Generics with legacy code" to Google