Java ArrayList: Generic Array Lists Explained
Use Java's ArrayList, the resizable array: declaring ArrayList<Employee> with var and the diamond operator, add, get, set, insert and remove, size versus capacity, ensureCapacity and trimToSize, for-each loops, converting to arrays, Java 21 getFirst/getLast, and raw-type compatibility.
kvi5hnuCode Sprout team member12 min readOn this page
In C and C++, array sizes are often fixed at compile time, which forces uncomfortable tradeoffs. How many employees will a department have? Surely no more than 100. And what about the huge department with 150 employees? Do you waste 90 slots for every department with only 10?
Java is better: you can set an array's size at runtime:
int actualSize = . . .;
var staff = new Employee[actualSize];
That helps only if you know the size before creating the array. An array's length is fixed for its whole life; if the number of employees grows afterwards, you must allocate a bigger array and copy everything yourself. ArrayList does that bookkeeping for you: it behaves like an array that grows and shrinks as elements are added and removed. It is the collection Java programs use most.
The element type goes in angle brackets, as in ArrayList<Employee>: ArrayList is a generic class, and Employee is its type argument. Writing generic classes yourself is a topic for the generics part; using ArrayList needs none of that.
Declaring Array Lists
Here's how to declare and construct an array list that holds Employee objects:
ArrayList<Employee> staff = new ArrayList<Employee>();
Use var to avoid repeating the type:
var staff = new ArrayList<Employee>();
Without var, you can omit the type argument on the right-hand side:
ArrayList<Employee> staff = new ArrayList<>();
The empty <> is called the diamond (it resembles one). The compiler looks at where the new object goes: a variable, a method parameter, or a return value. It fills in the matching type. Here the new list is assigned to a variable of type ArrayList<Employee>, so the type argument is Employee.
In practice, many developers declare variables with the interface type: List<Employee> staff = new ArrayList<>();. Then the code depends only on list operations and can switch implementations later. Interfaces and the collections framework come in later parts. Everything in this article works the same with a List variable.
Adding Elements, Size and Capacity
Use add to append elements:
staff.add(new Employee("Omar Haddad", . . .));
staff.add(new Employee("Lena Fischer", . . .));
Behind the scenes an array list keeps an ordinary array of references, usually with some unused slots at the end. When an add finds no free slot, the list allocates a larger array (about 1.5 times as big in OpenJDK) and copies all references over. Growth is cheap on average (amortized constant time per add), but each regrowth copies everything.

If you know, or can guess, how many elements you'll store, call ensureCapacity before filling the list:
staff.ensureCapacity(100);
That allocates an internal array of 100 references, so the first 100 calls to add won't trigger any costly reallocation. You can also pass an initial capacity to the constructor:
ArrayList<Employee> staff = new ArrayList<>(100);
The size method returns the number of elements actually in the list:
staff.size() // the equivalent of a.length for an array a
Once you're sure the list has reached its permanent size, you can call trimToSize. It shrinks the internal array to exactly the number of elements, and the garbage collector reclaims the excess memory. Adding elements afterward moves the block again, which takes time, so only trim when you're sure no more elements will come. (In everyday code, you rarely need ensureCapacity or trimToSize.)
Accessing Elements
Nothing comes for free. Automatic growth requires a clumsier syntax for element access, because ArrayList isn't part of the language. It's just a utility class in the standard library. Instead of [], you use get and set:
| Array | Array list |
|---|---|
a[i] = omar; | staff.set(i, omar); |
Employee e = a[i]; | Employee e = staff.get(i); |
a.length | staff.size() |
As with arrays, indexes start at 0. An invalid index throws IndexOutOfBoundsException.
Inserting and removing in the middle
To insert an element in the middle, use add with an index:
int n = staff.size() / 2;
staff.add(n, e);
The elements at positions n and above shift up to make room. If the new size exceeds the capacity, the storage array is reallocated. Similarly, you can remove an element from the middle:
Employee e = staff.remove(n);
The elements above it are copied down, and the size shrinks by one. There's also remove(Object), which removes the first element that equals the argument. Careful with ArrayList<Integer>: list.remove(1) removes the element at index 1, while list.remove(Integer.valueOf(1)) removes the value 1.
Inserting and removing in the middle isn't efficient: each operation shifts up to size() elements, which is O(n). That doesn't matter for small lists. If you store many elements and frequently insert and remove in the middle, other collections may fit better; see the collections part. (Often, though, ArrayList still wins in practice because its memory layout is cache-friendly.)
Traversing
Use the "for each" loop:
for (Employee e : staff) {
// do something with e
}
It has the same effect as
for (int i = 0; i < staff.size(); i++) {
Employee e = staff.get(i);
// do something with e
}
Don't add or remove elements while iterating with "for each". That usually throws a ConcurrentModificationException, and when it doesn't (removing the second-to-last element, for example, just ends the loop early), elements are silently skipped. Use removeIf (below) or an explicit iterator instead.
Getting the best of both: list, then array
Sometimes you want flexible growth while collecting, and an array afterward. First, add all the elements to an array list:
var list = new ArrayList<X>();
while (. . .) {
x = . . .;
list.add(x);
}
When you're done, copy the elements into an array with toArray:
var a = new X[list.size()];
list.toArray(a);
Shorter modern forms: X[] a = list.toArray(new X[0]); or, since Java 11, X[] a = list.toArray(X[]::new);.
More useful methods
Array lists have many more convenient methods, covered in depth in the collections part. A preview:
| Method | Purpose |
|---|---|
contains(o), indexOf(o) | Search (using equals) |
isEmpty(), clear() | Test for or remove all elements |
addAll(collection) | Append many elements |
sort(comparator) | Sort in place, e.g. staff.sort(Comparator.comparing(Employee::getName)) |
removeIf(predicate) | Remove matching elements: staff.removeIf(e -> e.getSalary() < 45000) |
getFirst(), getLast(), removeFirst(), removeLast(), reversed() | Java 21 sequenced-collection methods |
List.of(a, b, c) | Create an unmodifiable list (Java 9+) |
new ArrayList<>(List.of(a, b, c)) | Create a modifiable list with initial elements |
The Employee Program with an Array List
Below, the first staff program from Part 4 is rewritten with an ArrayList<Employee>. Compared with the array version:
| Array | ArrayList |
|---|---|
new Employee[3], size fixed up front | new ArrayList<>(), no size needed |
staff[i] = e into a free slot | staff.add(e), as often as you like |
staff.length | staff.size() |
staff[i] | staff.get(i) |
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class Solution {
public static void main(String[] args) {
// fill the staff array list with three Employee objects
var staff = new ArrayList<Employee>();
staff.add(new Employee("Priya Nair", 68000, 2016, 4, 11));
staff.add(new Employee("Omar Haddad", 52000, 2019, 9, 2));
staff.add(new Employee("Lena Fischer", 46000, 2021, 6, 21));
// raise everyone's salary by 4%
for (Employee e : staff) {
e.giveRaise(4);
}
// print out information about all Employee objects
for (Employee e : staff) {
System.out.println("name=" + e.getName() + ",salary=" + e.getSalary()
+ ",startDate=" + e.getStartDate());
}
System.out.println("size: " + staff.size());
// insert, replace, remove
staff.add(1, new Employee("Ada Lovelace", 90000, 2020, 1, 6));
Employee old = staff.set(3, new Employee("Rosa Lima", 41000, 2024, 4, 1));
Employee removed = staff.remove(0);
System.out.println("replaced " + old.getName() + ", removed " + removed.getName());
for (int i = 0; i < staff.size(); i++) {
System.out.println(i + ": " + staff.get(i).getName());
}
// Java 21 sequenced collections, sorting, removeIf
System.out.println(staff.getFirst().getName() + " ... " + staff.getLast().getName());
staff.sort(Comparator.comparing(Employee::getName));
staff.removeIf(e -> e.getSalary() < 45000);
System.out.println(staff.stream().map(Employee::getName).toList());
// copy into an array
Employee[] array = staff.toArray(new Employee[0]);
System.out.println(array.length + " " + array[0].getName());
// capacity is not size
var list = new ArrayList<String>(100);
System.out.println("size after new ArrayList<>(100): " + list.size());
try {
list.set(0, "x");
} catch (IndexOutOfBoundsException ex) {
System.out.println(ex.getMessage());
}
// var with diamond gives ArrayList<Object>
var elements = new ArrayList<>();
elements.add("text");
elements.add(42);
System.out.println(elements);
// unmodifiable lists
List<String> fixed = List.of("a", "b");
try {
fixed.add("c");
} catch (UnsupportedOperationException ex) {
System.out.println("List.of is unmodifiable");
}
}
}
class Employee {
private final String name;
private double salary;
private final LocalDate startDate;
public Employee(String name, double salary, int year, int month, int day) {
this.name = name;
this.salary = salary;
startDate = LocalDate.of(year, month, day);
}
public String getName() { return name; }
public double getSalary() { return salary; }
public LocalDate getStartDate() { return startDate; }
public void giveRaise(double pct) {
double raise = salary * pct / 100;
salary += raise;
}
}
name=Priya Nair,salary=70720.0,startDate=2016-04-11
name=Omar Haddad,salary=54080.0,startDate=2019-09-02
name=Lena Fischer,salary=47840.0,startDate=2021-06-21
size: 3
replaced Lena Fischer, removed Priya Nair
0: Ada Lovelace
1: Omar Haddad
2: Rosa Lima
Ada Lovelace ... Rosa Lima
[Ada Lovelace, Omar Haddad]
2 Ada Lovelace
size after new ArrayList<>(100): 0
Index 0 out of bounds for length 0
[text, 42]
List.of is unmodifiable
(The lambda expressions e -> ... and method references Employee::getName are explained in the next part. For now, read them as "for each employee e, test this" and "use the employee's name".)
The ArrayList API at a Glance
java.util.ArrayList<E>:
| Method | Description |
|---|---|
ArrayList<E>() | Constructs an empty array list |
ArrayList<E>(int initialCapacity) | Constructs an empty array list with the given capacity |
boolean add(E obj) | Appends obj at the end; always returns true |
void add(int index, E obj) | Inserts obj at index, shifting later elements up |
E get(int index) | Returns the element at index |
E set(int index, E obj) | Replaces the element at index with obj and returns the old one |
E remove(int index) | Removes and returns the element at index, shifting later elements down |
int size() | Returns the number of elements (never larger than the capacity) |
void ensureCapacity(int capacity) | Ensures the list can hold capacity elements without reallocating |
void trimToSize() | Reduces the capacity to the current size |
Compatibility Between Typed and Raw Array Lists
New code should always supply a type argument. Older libraries written before Java 5 don't, and you may have to call them. Imagine a class like this:
public class LegacyRoster {
public void update(ArrayList list) { . . . }
public ArrayList find(String query) { . . . }
}
You can pass a typed array list to update without any cast:
ArrayList<Employee> staff = . . .;
roster.update(staff);
The compiler doesn't complain, but the call isn't completely safe. update might add elements that aren't Employee objects, and retrieving them later throws an exception:
Exception in thread "main" java.lang.ClassCastException: class java.lang.String cannot be cast to class Employee
That sounds scary, but it's simply how things were before generics existed. The integrity of the virtual machine is never at risk. You don't lose safety, but you don't get the compile-time checks either.
Conversely, assigning a raw list to a typed variable produces a warning:
ArrayList<Employee> result = roster.find(query); // warning: [unchecked] unchecked conversion
(Compile with -Xlint:unchecked to see the full text of such warnings.) A cast doesn't make the warning go away; you get a different one, saying the cast is misleading:
ArrayList<Employee> result = (ArrayList<Employee>) roster.find(query); // warning: [unchecked] unchecked cast
The cast can't help because of type erasure. The compiler uses <Employee> for its own checks and then drops it; the bytecode works with plain ArrayList. At run time there is no way to tell an ArrayList<Employee> from an ArrayList<String>, so a cast to ArrayList<Employee> can only verify "is an ArrayList", exactly like a cast to the raw type.
There isn't much you can do about it. When working with legacy code, study the warnings and satisfy yourself that they aren't serious. Then annotate the receiving variable with @SuppressWarnings("unchecked"):
@SuppressWarnings("unchecked") ArrayList<Employee> result
= (ArrayList<Employee>) roster.find(query); // yields no warning
Keep the annotation's scope as small as possible: a single variable declaration, not a whole class.
Common questions
Should I declare variables as ArrayList or List?
Usually List<Employee> staff = new ArrayList<>();. Code that depends only on the List interface works with any implementation and with immutable lists from List.of. Use ArrayList as the declared type only when you need ArrayList-specific methods such as ensureCapacity or trimToSize.
What's the difference between List.of(...) and new ArrayList<>(...)?
List.of creates an unmodifiable list: add, set and remove throw UnsupportedOperationException, and null elements aren't allowed. new ArrayList<>(List.of(...)) gives you a modifiable copy. Arrays.asList is a third variant: a fixed-size view of an array that allows set but not add or remove.
How do I get the first or last element of a list?
Since Java 21 (sequenced collections), use list.getFirst() and list.getLast(), plus removeFirst(), removeLast(), addFirst(...) and reversed(). On older versions, write list.get(0) and list.get(list.size() - 1). getFirst, getLast, removeFirst and removeLast throw NoSuchElementException on an empty list (and get(0) throws IndexOutOfBoundsException), so check isEmpty() first when the list might be empty.
Is ArrayList thread-safe?
No. Concurrent modification from several threads can corrupt it or throw ConcurrentModificationException. Use Collections.synchronizedList, CopyOnWriteArrayList (for read-mostly lists), or better, avoid sharing mutable lists between threads.
Why does removing elements in a for-each loop throw?
The iterator detects that the list was modified behind its back and throws ConcurrentModificationException. Use list.removeIf(e -> condition), or an explicit Iterator and its remove() method.
Summary
ArrayList<E>is a resizable array. Declare it withvar staff = new ArrayList<Employee>();orArrayList<Employee> staff = new ArrayList<>();, but not withvarand the diamond together.- Use
addto append or insert,getandsetto read and replace,removeto delete, andsize()for the element count. - Capacity ≠ size.
new ArrayList<>(100)is empty.ensureCapacityandtrimToSizetune the internal array. - Inserting and removing in the middle shifts elements (O(n)). Don't modify a list while iterating over it with for-each.
- Convert to an array with
toArray(new X[0])ortoArray(X[]::new). Java 21 addsgetFirst,getLastandreversed. - Raw
ArrayListexists for legacy code. Generics are erased at runtime, so mixing raw and typed lists gives unchecked warnings; suppress them only after checking.
Practice Questions
What's printed? var list = new ArrayList<String>(10); System.out.println(list.size());
0. The constructor argument is the initial capacity, not the size. The list starts empty.
ArrayList<Integer> nums = new ArrayList<>(List.of(10, 20, 30)); What does nums.remove(1) do? And nums.remove(Integer.valueOf(10))?
remove(1) removes the element at index 1 (20), leaving [10, 30]. remove(Integer.valueOf(10)) removes the value 10, leaving [30].
Why does var items = new ArrayList<>(); items.add("a"); String s = items.get(0); fail to compile?
With var and the diamond, the list is an ArrayList<Object>, so get returns Object, which can't be assigned to String without a cast. Write new ArrayList<String>().
How do you convert an ArrayList<String> names into a String[]?
String[] arr = names.toArray(new String[0]); or, since Java 11, String[] arr = names.toArray(String[]::new);.
Why can't the JVM tell an ArrayList<Employee> from an ArrayList<String> at runtime?
Type erasure: the compiler checks generic types and then erases them, so at runtime both are plain ArrayList objects. That's why a cast to ArrayList<Employee> is unchecked and produces a warning.
Previous: Java hashCode and toString: Writing Them Correctly
Related reading
- Java ConcurrentHashMap, CopyOnWriteArrayList and Parallel Array Algorithms
- Java Blocking Queues and Thread-Safe Collections: Producer-Consumer Made Easy
- Java hashCode and toString: Writing Them Correctly
- Java Object Class and the equals Method
- Java final Classes and Methods, Casting, instanceof Patterns and protected Access

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.