in

ArrayList in Java: A Comprehensive Guide for Beginners [2025]

ArrayList in Java

Arrays are one of the most commonly used data structures in programming. But in languages like Java, arrays have a fixed size that is declared at initialization. This can be problematic when the size of the data is not known beforehand.

To address this limitation, Java provides dynamic arrays called ArrayLists. The size of an ArrayList grows automatically as elements are added. This makes them extremely useful when working with collections of data.

In this comprehensive guide, I will walk you through everything you need to know about ArrayLists in Java. I will explain:

  • The basics of arrays vs ArrayLists
  • How to create and initialize an ArrayList
  • Useful methods to add, retrieve, update and delete elements
  • Difference between ArrayLists and LinkedLists
  • How to loop through an ArrayList
  • Sorting and converting an ArrayList

And much more.

So if you‘re looking to master ArrayLists in Java, you‘re in the right place. Let‘s begin!

Array vs ArrayList

An array is the most basic data structure in Java. It stores elements of the same data type in a contiguous block of memory.

But the major limitation of arrays is that their size is fixed when they are created.

For example:

// Create an array of 5 elements 
int[] numbers = new int[5];

Once you initialize this array to a size of 5 elements, you cannot change its size at runtime.

This is where ArrayLists come in.

ArrayLists are dynamic arrays that overcome this limitation. Their size can grow and shrink at runtime automatically as you add or remove elements.

Below is a quick comparison between standard arrays and ArrayLists:

Feature Array ArrayList
Size Fixed Dynamic
Primitives allowed Yes No, only objects
Multidimensional Yes No, single dimensional
Part of collections framework No Yes

Some key points:

  • Array size is fixed, ArrayList size is flexible
  • Arrays allow primitives like int, char etc. ArrayLists don‘t allow primitives directly but can store their wrapper classes like Integer.
  • Multidimensional arrays are possible but ArrayLists are always single dimensional.
  • ArrayList is part of the Collections framework in Java which provides many useful methods to work with them.

So in summary, ArrayLists provide flexibility that static arrays lack while retaining most of their functionality.

Creating an ArrayList

ArrayLists are generic classes so you need to provide the type during declaration:

ArrayList<Type> list = new ArrayList<>();

For example:

import java.util.ArrayList;

ArrayList<String> fruits = new ArrayList<>();

This declares an ArrayList of Strings called fruits.

To use ArrayLists, you need to import java.util.ArrayList.

You can also initialize the ArrayList with some default values:

ArrayList<Integer> numbers = new ArrayList<>(List.of(1,2,3));

This creates an ArrayList called numbers and initializes it with the values 1, 2 and 3.

The default initial capacity of an ArrayList is 10. But you can also specify the initial capacity:

ArrayList<String> names = new ArrayList<>(30); //Initial capacity 30

The initial capacity is the number of elements the ArrayList can hold before it needs to resize internally. Specifying larger capacities upfront can reduce the overhead of resizing for large ArrayLists.

Adding Elements

To add elements to an ArrayList, use the add() method:

arrayList.add(element);

This adds the element to the end of the ArrayList.

You can also insert an element at a specific index:

arrayList.add(index, element);

For example:

fruits.add("Apple");
fruits.add(0, "Banana"); 

System.out.println(fruits);

// Output: [Banana, Apple] 

add() returns true if the element was added successfully.

Useful Tips

  • Inserting at an index shifts all subsequent elements to the right.
  • Inserting past the current size will expand the ArrayList capacity.
  • Inserting null values is allowed in ArrayLists.

Accessing Elements

To access an element at a specific index, use get(index):

String fruit = fruits.get(0); // Returns "Banana"

This returns the element at the specified index.

To modify an element:

fruits.set(0, "Orange"); 

This sets index 0 to a new value, replacing the existing element.

Some things to keep in mind:

  • If the index is invalid, get() and set() will throw an IndexOutOfBoundsException
  • set() overwrites the existing element at that index if any.

Removing Elements

To remove an element from a specific index:

fruits.remove(0); // Remove first element

To remove a specific element value:

fruits.remove("Apple");

This removes the first occurrence of "Apple".

You can remove all elements with:

fruits.clear();

Important notes on remove():

  • Removing an element shifts subsequent elements to the left index wise.
  • If the element does not exist, remove() will return false.
  • clear() shrinks the ArrayList size to 0 but does not deallocate the backing array.

ArrayList Size and Length

To get the number of elements in an ArrayList, use the size() method:

int length = fruits.size();

This returns the total number of elements currently in the ArrayList.

Some things to keep in mind about size:

  • size() takes constant time O(1) as the ArrayList maintains an internal count.
  • The size increases when elements are added and decreases when removed.
  • The size can be 0 if no elements are present.
  • The size doubles automatically when adding past the capacity.

Looping Through an ArrayList

You can loop through ArrayList elements using a standard for loop with index:

for(int i = 0; i < fruits.size(); i++) {
  System.out.println(fruits.get(i));
}

Or use the enhanced for-each loop:

for(String fruit : fruits) {
  System.out.println(fruit);
} 

Iterating through an ArrayList allows you to perform any operations on its elements.

Some tips on iterating ArrayLists:

  • Use size() method directly rather than calculating length manually.
  • For-each loop avoids needing index access.
  • For-each loop uses iterators internally.
  • Removing elements during iteration can cause bugs.

Sorting an ArrayList

To sort an ArrayList, you can use the sort() method from the Collections class:

Collections.sort(fruits);  

This will sort the ArrayList alphabetically for Strings, or numerically for number types.

You can also provide a custom comparator to control how the sorting is done:

Collections.sort(fruits, new Comparator<String>() {
  // Custom comparison logic
});

Important things to note about sorting:

  • Sorting is done in-place, meaning the original ArrayList is modified.
  • The default sort uses alphabetical order for strings, numerical for numbers.
  • For custom sorting logic, provide a Comparator.
  • Sorting takes O(n log n) time for ArrayLists.

Converting ArrayList to Array

You can convert an ArrayList to an array using the toArray() method:

String[] array = fruits.toArray(new String[0]);

The argument specifies the type of array to return.

Some important points:

  • toArray() returns the standard system array, not a wrapper array.
  • The returned array‘s length is equal to the ArrayList size.
  • Changes to the returned array don‘t affect the original ArrayList.

ArrayList vs LinkedList

ArrayLists and LinkedLists both implement the List interface, but have some key differences:

  • Access: ArrayLists support fast random access, LinkedLists support sequential access.

  • Insertions/deletions: LinkedLists are faster for insertions and deletions, ArrayLists require shifting elements.

  • Memory: ArrayLists store elements in an array, LinkedLists use node chains requiring more memory per element.

  • Performance: ArrayLists have better get/set performance, LinkedLists have better add/remove performance.

So in summary, if you need more modifications like additions/removals to the list and less random access, LinkedList tends to perform better.

But ArrayLists should be your default choice otherwise for their simplicity and fast lookups.

Internal Implementation

Under the hood, ArrayLists are implemented using resizable arrays in Java:

  • The backing array starts with a capacity of 10.
  • When the number of elements reaches this capacity, a new larger array is created and elements copied over.
  • The size doubles each time the backing array needs to resize.
  • Resizing takes O(n) time as elements must be copied over.
  • Methods like get, set, iterate are O(1) thanks to direct array access.

So ArrayLists combine the benefits of array access with the flexibility of dynamic sizing. But this comes at the cost of resizing overheads.

Use Cases

Some good use cases of ArrayLists are:

  • Storing simple collections of objects/data
  • Dynamically updated lists where size is not known
  • Fetching random elements efficiently
  • Adding or removing from edges efficiently
  • Shuffling/randomizing lists of objects

ArrayLists are the standard default choice for dynamic arrays in Java.

Conclusion

ArrayLists are one of the most commonly used data structures in Java. Their dynamic resizing, usefulness of methods, and speed makes them very versatile.

Here are some key takeaways:

  • ArrayLists are dynamically sized unlike fixed length arrays.
  • They allow storing objects/data and provide useful methods like add(), get(), remove() etc.
  • ArrayLists allow fast random access but adding/removing requires shifting elements.
  • Prefer LinkedLists if you need frequent additions/removals from the middle.
  • For most other use cases, ArrayLists should be the default choice.

I hope this comprehensive guide gives you a deep understanding of ArrayLists in Java. They are critical to mastering data structures and collections in Java.

Let me know in the comments if you have any other ArrayList questions!

AlexisKestler

Written by Alexis Kestler

A female web designer and programmer - Now is a 36-year IT professional with over 15 years of experience living in NorCal. I enjoy keeping my feet wet in the world of technology through reading, working, and researching topics that pique my interest.