View RSS Feed

Advanced Java

Use Lists instead Arrays in Generics

Rate this Entry
by , 11-29-2011 at 11:20 PM (1812 Views)
Generics were added to java in release 1.5. It allows you to avoid needing to cast objects as they are read from a collection. Instead you tell the compiler what types of objects that you want to hold in the collection. Often it is difficult to know which generic to use when you have two or more who seem to be able to complete the same function. Consider the choice between whether to use a list or an array. Now a key thing to remember is that arrays are covariant and know and enforce their element types at runtime, while generics are invariant and enforce their type constraints at compile time (discarding this information) at runtime. What this means is that it is not possible to create a generic array since it will result in generic array creation errors at compile time. So it is always recommended to use lists instead of arrays when you have a choice between the two.

The general principle is to use an List everywhere that you are tempted to create an array of generics

Java Code:
public class ArrayExample<T> {
	private List<T> array = new ArrayList<T>();

	public void add(T item) {
		array.add(item);
	}

	public T get(int index) {
		return array.get(index);
	}
}

Submit "Use Lists instead Arrays in Generics" to Facebook Submit "Use Lists instead Arrays in Generics" to Digg Submit "Use Lists instead Arrays in Generics" to del.icio.us Submit "Use Lists instead Arrays in Generics" to StumbleUpon Submit "Use Lists instead Arrays in Generics" to Google

Comments