ArrayList v/s ArrayList

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

 

ArrayList v/s ArrayList<T>:

ArrayList

ArrayList<T>

This is non-generics version of ArrayList This 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 ArrayList It 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 Objects In 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

 

Example 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

 

Example 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.

 

References:

 

Happy Coding !!
Happy Learning !!

Generics interview question and answer in Java