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

Java allows us to create arrays of fixed size or use collection classes to do a similar job.

In this tutorial, we’re going to look at the difference between the capacity of an ArrayList and the size of an Array.

We’ll also look at examples of when we should initialize ArrayList with a capacity and the benefits and disadvantages in terms of memory usage.

2. Example

To understand the differences, let’s first try both options.

2.1. Size of an Array

In java, it’s mandatory to specify the size of an array while creating a new instance of it:

Integer[] array = new Integer[100]; 
System.out.println("Size of an array:" + array.length);

Here, we created an Integer array of size 100, which resulted in the below output

Size of an array:100

2.2. Capacity of an ArrayList

Technically, the default capacity (DEFAULT_CAPACITY) of a newly created ArrayList is 10. However, Java 8 changed how this initial capacity is used for performance reasons.

It’s not used immediately and is guaranteed lazily once a new item is added to the list.

So, the default capacity of an empty ArrayList is 0 and not 10 in Java 8. Once the first item is added, the DEFAULT_CAPACITY which is 10 is then used.

Since there is no built-in method to get the default capacity, let’s use reflection to return it:

public static int getDefaultCapacity(ArrayList<?> arrayList) throws Exception {

    if (arrayList == null) {
        return 0;
    }

    Field field = ArrayList.class.getDeclaredField("elementData");
    field.setAccessible(true);

    return ((Object[]) field.get(arrayList)).length;
}

Now, let’s confirm that the default capacity of an empty ArrayList is 0:

@Test
void givenEmptyArrayList_whenGetDefaultCapacity_thenReturnZero() throws Exception {

    ArrayList<Integer> myList = new ArrayList<>();
    int defaultCapacity = DefaultArrayListCapacity.getDefaultCapacity(myList);

    assertEquals(0, defaultCapacity);
}

Next, let’s see what happens when we add a new item to an empty ArrayList:

@Test
void givenEmptyArrayList_whenAddItemAndGetDefaultCapacity_thenReturn10() throws Exception {

    ArrayList<String> myList = new ArrayList<>();
    myList.add("ITEM 1");

    int defaultCapacity = DefaultArrayListCapacity.getDefaultCapacity(myList);

    assertEquals(10, defaultCapacity);
}

The purpose of this change in Java 8 is to save memory consumption and avoid immediate memory allocation.

Now, let’s create an ArrayList with an initial capacity of 100:

List<Integer> list = new ArrayList<>(100);
assertEquals(0, list.size());

As no elements have been added yet, the size is zero.

Now, let’s add an element to the list and check its size:

list.add(10);
assertEquals(1, list.size());

3. Size in Arrays vs. ArrayList

Below are some major differences between the size of an array and the capacity of an ArrayList.

3.1. Modification of Size

Arrays are fixed size. Once we initialize the array with some int value as its size, it can’t change. The size and capacity are equal to each other too.

ArrayList‘s size and capacity are not fixed. The logical size of the list changes based on the insertion and removal of elements in it. This is managed separately from its physical storage size. Also when the threshold of ArrayList capacity is reached, it increases its capacity to make room for more elements.

3.2. Memory Allocation

Array memory is allocated on creation. When we initialize an array, it allocates the memory according to the size and type of an array. It initializes all the elements with a null value for reference types and the default value for primitive types.

ArrayList changes memory allocation as it grows. When we specify the capacity while initializing the ArrayList, it allocates enough memory to store objects up to that capacity. The logical size remains 0. When it is time to expand the capacity, a new, larger array is created, and the values are copied to it.

We should note that there’s a special singleton 0-sized array for empty ArrayList objects, making them very cheap to create. It’s also worth noting that ArrayList internally uses an array of Object references.

4. When to Initialize ArrayList with Capacity

We may expect to initialize the capacity of an ArrayList when we know its required size before we create it, but it’s not usually necessary. However, there are a few reasons why this may be the best option.

4.1. Building a Large ArrayList

It is good to initialize a list with an initial capacity when we know that it will get large. This prevents some costly grow operations as we add elements.

Similarly, if the list is very large, the automatic grow operations may allocate more memory than necessary for the exact maximum size. This is because the amount to grow each time is calculated as a proportion of the size so far. So, with large lists, this could result in a waste of memory.

4.2. Building Small Multiple ArrayLists

If we have a lot of small collections, then the automatic capacity of an ArrayList may provide a large percentage of wasted memory. Let’s say that ArrayList prefers a size of 10 with smaller numbers of elements, but we are only storing 2 or 3. That means 70% wasted memory, which might matter if we have a huge number of these lists.

Setting the capacity upfront can avoid this situation.

5. Avoiding Waste

We should note that ArrayList is a good solution for a flexible-sized container of objects that is to support random access. It consumes slightly more memory than an array but provides a richer set of operations.

In some use cases, especially around large collections of primitive values, the standard array may be faster and use less memory.

Similarly, for storing a variable number of elements that do not need to be accessed by index, LinkedList can be more performant. It does not come with any overhead of memory management.

6. Summary

In this short article, we saw the difference between the capacity of the ArrayList and the size of an array. We also looked at when we should initialize the ArrayList with capacity and its benefits with regards to memory usage and performance.

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)
2 Comments
Oldest
Newest
Inline Feedbacks
View all comments