eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

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

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

1. Introduction

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

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

Finally, we’ll see how 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;
}

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 just assigned an Object[] to a String[] reference. Specifically, an implicit cast by the compiler will fail to convert Object[] to our required type String[].

Although we can’t initialize generic arrays directly, it’s 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. As we’d like the stack to work with any type, a reasonable implementation choice would be a generic array.

First, we’ll create a field to store the elements of our stack, which is a generic array of type E:

private E[] elements;

Then we’ll 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, we’ll create a field to store our elements:

private List<E> elements;

Then, 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. 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 isn’t 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, we’ll 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");

Then we’ll build an array of the items we 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 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, we’ll look at the method signature:

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

Then we’ll 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 previous stack example. We can also see that 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 ensure we 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"))
  .toArray();

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:

assertThat(strings).isNotInstanceOf(String[].class);

As we saw earlier, the precise type of each array is different. As the type in a Stream is generics, there’s no way for the library to infer 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"))
  .toArray(String[]::new);

assertThat(strings).containsExactly("A", "AAA", "AAB");
assertThat(strings).isInstanceOf(String[].class);

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"))
  .map(Optional::of);

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

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

Luckily, there’s a difference between this example and our previous examples. Where String[] isn’t 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"))
  .map(Optional::of);
Optional<String>[] strings = stream
  .toArray(Optional[]::new);

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

@SuppressWarnings("unchecked")

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 can write a helper function:

@SuppressWarnings("unchecked")
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"))
  .map(Optional::of)
  .toArray(genericArray(Optional[]::new));

The unchecked assignment warning doesn’t 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"))
  .toArray(genericArray(List[]::new));

This would compile, but would throw a ClassCastException, as ArrayList[] isn’t 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 examined the differences between arrays and generics. Then we looked at an example of creating a generic array, demonstrating how using an ArrayList may be easier than using a generic array. We also discussed the use of a generic array in the Collections API.

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

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

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

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)