1. Introduction

We may wish to use arrays as part of classes or functions that support generics. Due to the way Java handles generics, this can be difficult.

In this tutorial, we'll understand the challenges of using generics with arrays. Then, we'll create an example of a generic array.

We'll also look at where the Java API has solved a similar problem.

2. Considerations When Using Generic Arrays

An important difference between arrays and generics is how they enforce type checking. Specifically, arrays store and check type information at runtime. Generics, however, check for type errors at compile-time and don't have type information at runtime.

Java's syntax suggests we might be able to create a new generic array:

T[] elements = new T[size];

But, if we attempted this, we'd get a compile error.

To understand why, let's consider the following:

public <T> T[] getArray(int size) {
    T[] genericArray = new T[size]; // suppose this is allowed
    return genericArray;

As an unbound generic type T resolves to Object, our method at runtime will be:

public Object[] getArray(int size) {
    Object[] genericArray = new Object[size];
    return genericArray;

Then, if we call our method and store the result in a String array:

String[] myArray = getArray(5);

The code will compile fine but fail at runtime with a ClassCastException. This is because we've just assigned an Object[] to a String[] reference. Specifically, an implicit cast by the compiler would fail to convert Object[] to our required type String[].

Although we can't initialize generic arrays directly, it is still possible to achieve the equivalent operation if the precise type of information is provided by the calling code.

3. Creating a Generic Array

For our example, let's consider a bounded stack data structure MyStack, where the capacity is fixed to a certain size. Also, as we'd like the stack to work with any type, a reasonable implementation choice would be a generic array.

First, let's create a field to store the elements of our stack, which is a generic array of type E:

private E[] elements;

Second, let's add a constructor:

public MyStack(Class<E> clazz, int capacity) {
    elements = (E[]) Array.newInstance(clazz, capacity);

Notice how we use java.lang.reflect.Array#newInstance to initialize our generic array, which requires two parameters. The first parameter specifies the type of object inside the new array. The second parameter specifies how much space to create for the array. As the result of Array#newInstance is of type Object, we need to cast it to E[] to create our generic array.

We should also note the convention of naming a type parameter clazz rather than class, which is a reserved word in Java.

4. Considering ArrayList

4.1. Using ArrayList in Place of an Array

It's often easier to use a generic ArrayList in place of a generic array. Let's see how we can change MyStack to use an ArrayList.

First, let's create a field to store our elements:

private List<E> elements;

Secondly, in our stack constructor, we can initialize the ArrayList with an initial capacity:

elements = new ArrayList<>(capacity);

It makes our class simpler, as we don't have to use reflection. Also, we aren't required to pass in a class literal when creating our stack. Finally, as we can set the initial capacity of an ArrayList, we can get the same benefits as an array.

Therefore, we only need to construct arrays of generics in rare situations or when we're interfacing with some external library that requires an array.

4.2. ArrayList Implementation

Interestingly, ArrayList itself is implemented using generic arrays. Let's peek inside ArrayList to see how.

First, let's see the list elements field:

transient Object[] elementData;

Notice ArrayList uses Object as the element type. As our generic type is not known until runtime, Object is used as the superclass of any type.

It's worth noting that nearly all the operations in ArrayList can use this generic array as they don't need to provide a strongly typed array to the outside world, except for one method – toArray!

5. Building an Array from a Collection

5.1. LinkedList Example

Let's look at using generic arrays in the Java Collections API, where we'll build a new array from a collection.

First, let's create a new LinkedList with a type argument String and add items to it:

List<String> items = new LinkedList();
items.add("first item");
items.add("second item");

Second, let's build an array of the items we've just added:

String[] itemsAsArray = items.toArray(new String[0]);

To build our array, the List.toArray method requires an input array. It uses this array purely to get the type information to create a return array of the right type.

In our example above, we've used new String[0] as our input array to build the resulting String array.

5.2. LinkedList.toArray Implementation

Let's take a peek inside LinkedList.toArray, to see how it's implemented in the Java JDK.

First, let's look at the method signature:

public <T> T[] toArray(T[] a)

Second, let's see how a new array is created when required:

a = (T[])java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), size);

Notice how it makes use of Array#newInstance to build a new array, like in our stack example earlier. Also, notice how parameter a is used to provide a type to Array#newInstance. Finally, the result from Array#newInstance is cast to T[] create a generic array.

6. Conclusion

In this article, we first looked at the differences between arrays and generics, followed by an example of creating a generic array. Then, we showed how using an ArrayList may be easier than using a generic array. Finally, we also looked at the use of a generic array in the Collections API.

As always, the example code is available over on GitHub.

Generic bottom

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

Comments are closed on this article!