Amit Kumar Mondal bio photo

Amit Kumar Mondal

Java Enthusiast

Email Facebook Google+ LinkedIn Github

Overview

Overview

Reification signifies the runtime component representation. Any type which can be completely represented at runtime is known as Reifiable Type

Eg, A primitive type, non-parameterized class or interface type, parameterized type of unbounded wildcard (

List<?>

), raw type (List), Array whose component is reifiable (

List<?>[], int[], List[]

).

Arrays can reify their component types. It means array types can be represented properly at runtime.

Old School Example

public final class ArrayReification {

	public static void main(final String[] args) {
		final Integer[] integers = new Integer[5];
		final Number[] numbers = integers;
		numbers[0] = 1.1;
	}

}

Any clue about the problem that the application might encounter?

It suffers from ArrayStoreException at runtime because the actual array object has the component type of Integer which can not store any value of type Double.

Parameterized Array

Let’s have a look at the following snippet to transform a collection to an array..

public final class Helper {

	public static <T> T[] toArray(final Collection<T> collection) {
		final T[] arr = new T[collection.size()];
		int i = 0;
		for (final T val : collection) {
			arr[i++] = val;
		}
		return arr;
	}

}

Is the code correct?

No, it’s not. It will result in a compilation error.

Cannot create a generic array of T

The error occurs due to the type variable of not being a reifiable type. Hence, it reports compilation error at the generic array creation line in the snippet.

Let’s look at another example.

public final class ArrayOfList {

	public static void main(final String[] args) {
		final List<String> cars = asList("Audi", "BMW", "Kia", "Tata");
		final List<String> universities = asList("TU Munich", "RWTH Aachen", "Uni Stuttgart", "TU Kiel");
		final List<String>[] arrayOfLists = new List<String>[] { cars, universities };
	}
}

This program also suffers from the same compilation error.

Cannot create a generic array of List<String>

The error happens because List<String%gt; is not a reifiable type.

Solution

So, can’t we use generic arrays for our purpose? No, we can use generic arrays but it is advisable to use any collection type to contain list of data which comprises more operations to be performed on the data container.

I just wanted not to get you inundated with each and every aspect of Array Reification, I kept this post as small as possible so that you can learn gradually. I would love to discuss more on Array Reification in my future posts to cover some of the important aspects on it.