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[] to create a generic array.

6. Creating Arrays From Streams

The Java Streams API allows us to create arrays from the items in the stream. There are a couple of pitfalls to watch out for to produce an array of the correct type.

6.1. Using toArray

We can easily convert the items from a Java 8 Stream into an array:

Object[] strings = Stream.of("A", "AAA", "B", "AAB", "C")
  .filter(string -> string.startsWith("A"))

assertThat(strings).containsExactly("A", "AAA", "AAB");

We should note, however, that the basic toArray function provides us with an array of Object, rather than an array of String:


As we saw earlier, the precise type of each array is different. As the type in a Stream is generics, there's no way of the library inferring the type at runtime.

6.2. Using the toArray Overload to Get a Typed Array

Where the common collection class methods use reflection to construct an array of a specific type, the Java Streams library uses a functional approach. We can pass in a lambda, or method reference, which creates an array of the correct size and type when the Stream is ready to populate it:

String[] strings = Stream.of("A", "AAA", "B", "AAB", "C")
  .filter(string -> string.startsWith("A"))

assertThat(strings).containsExactly("A", "AAA", "AAB");

The method we pass is an IntFunction which takes an integer as input and returns a new array of that size. This is exactly what the constructor of String[] does, so we can use the method reference – String[]::new.

6.3. Generics With Their Own Type Parameter

Now let's imagine we want to convert the values in our stream into an object which itself has a type parameter, say List or Optional. Perhaps we have an API we want to call that takes Optional<String>[] as its input.

It's valid to declare this sort of array:

Optional<String>[] strings = null;

We can also easily take our Stream<String> and convert it to Stream<Optional<String>> by using the map method:

Stream<Optional<String>> stream = Stream.of("A", "AAA", "B", "AAB", "C")
  .filter(string -> string.startsWith("A"))

However, we would again get a compiler error if we tried to construct our array:

// compiler error
Optional<String>[] strings = new Optional<String>[1];

Luckily, there is a difference between this example and our previous examples. Where String[] is not a subclass of Object[]Optional[] is actually an identical runtime type to Optional<String>[]. In other words, this is a problem we can solve by type casting:

Stream<Optional<String>> stream = Stream.of("A", "AAA", "B", "AAB", "C")
  .filter(string -> string.startsWith("A"))
Optional<String>[] strings = stream

This code compiles and works but gives us an unchecked assignment warning. We need to add a SuppressWarnings to our method to fix this:


6.4. Using a Helper Function

If we want to avoid adding the SuppressWarnings to multiple places in our code and wish to document the way our generic array is created from the raw type, we may wish to write a helper function:

static <T, R extends T> IntFunction<R[]> genericArray(IntFunction<T[]> arrayCreator) {
    return size -> (R[]) arrayCreator.apply(size);

This function converts the function to make an array of the raw type into a function that promises to make an array of the specific type we need:

Optional<String>[] strings = Stream.of("A", "AAA", "B", "AAB", "C")
  .filter(string -> string.startsWith("A"))

The unchecked assignment warning does not need to be suppressed here.

We should note, however, that this function can be called to perform type casts to higher types. For example, if our stream contained objects of type List<String>, we might incorrectly call genericArray to produce an array of ArrayList<String>:

ArrayList<String>[] lists = Stream.of(singletonList("A"))

This would compile but would throw a ClassCastException as ArrayList[] is not a subclass of List[]. The compiler produces an unchecked assignment warning for this, though, so it's easy to spot.

7. 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. We also looked at the use of a generic array in the Collections API.

Finally, we saw how to produce arrays from the Streams API and how to handle creating arrays of types that use a type parameter.

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!