Java 5 – ArrayList v/s Generic ArrayList

In this article, we will discuss the difference between non-generics & generics versions of ArrayList i.e.; ArrayList v/s ArrayList<T>

1. ArrayList v/s ArrayList<T>:

ArrayList

ArrayList<T>

This is non-generics version of ArrayListThis is generics version of ArrayList with type-parameter T
In this non-generics version, ArrayList allows to add any type of Objects like String, Integer, references-types, etc.But Generics version of ArrayList allows to add specific type of objects only

 

Like, if type-parameter T is replaced by String then only String-type of Objects are allowed to add to ArrayList

Basically, it doesn’t assures type-safety as any type of Objects can be added to ArrayListIt assures type-safety, as it allows to store same type of Objects only
During iteration of ArrayList, compulsorily explicit type-casting needs to be done even if ArrayList stores same type of ObjectsIn Generics version of ArrayList, no explicit type-casting is required

 

Reason: Generics ArrayList stores same type of Objects only, therefore type-casting isn’t required at the time of iteration or getting Objects

1.1 Non Generics version of ArrayList:

NonGenericsArrayList.java

package in.bench.resources.generics.demo;

import java.util.ArrayList;

public class NonGenericsArrayList {

	public static void main(String[] args) {

		// Non-Generics AL
		ArrayList al = new ArrayList();

		// add any values/objects to List
		al.add("one");
		al.add("two");
		al.add("four");
		al.add("eight");

		for(int index=0; index < al.size(); index++) {

			// explicit type-casting
			String str = (String) al.get(index);

			// print to console
			System.out.println(str);
		}
	}
}

Output:

one
two
four
eight

1.2 Generics version of ArrayList<T>:

GenericsArrayList.java

package in.bench.resources.generics.demo;

import java.util.ArrayList;

public class GenericsArrayList {

	public static void main(String[] args) {

		// Non-Generics AL
		ArrayList<String> al = new ArrayList<String>();

		// add any values/objects to List
		al.add("one");
		al.add("two");
		al.add("four");
		al.add("eight");

		for(int index=0; index < al.size(); index++) {

			// NO explicit type-casting
			String str = al.get(index);

			// print to console
			System.out.println(str);
		}
	}
}

Output:

one
two
four
eight

Hope, you found this article very helpful. If you have any suggestion or want to contribute or tricky situation you faced during Interview hours, then share with us. We will include that code here.

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java 8 – How to form ZonedDateTime passing LocalDate, LocalTime and ZoneId ?
Java 5 - Generics interview question and answers