A Java array has a fixed size chosen when it is created. An ArrayList is a resizable list that grows and shrinks as you add and remove items, which makes it the collection Java programmers use most often. This lesson covers creating a list, adding, reading, changing and removing elements, sorting, and the traps that catch beginners.
In this lesson you will learn
- Creating an
ArrayListwith generics add,get,set,removeandsize- Searching with
containsandindexOf - Sorting with
Collections.sortand comparators - Safe removal with
removeIfand immutable lists
Basic Operations
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> cities = new ArrayList<>();
cities.add("Dhaka");
cities.add("Sylhet");
cities.add("Khulna");
cities.add(1, "Chattogram"); // insert at index 1
System.out.println(cities + " size=" + cities.size());
System.out.println("get(2): " + cities.get(2));
cities.set(0, "Rajshahi"); // replace
cities.remove("Khulna"); // remove by value
System.out.println(cities);
System.out.println("contains Sylhet? " + cities.contains("Sylhet"));
System.out.println("indexOf Sylhet: " + cities.indexOf("Sylhet"));
for (int i = 0; i < cities.size(); i++) {
System.out.println(i + ": " + cities.get(i));
}
}
}
Output
[Dhaka, Chattogram, Sylhet, Khulna] size=4
get(2): Sylhet
[Rajshahi, Chattogram, Sylhet]
contains Sylhet? true
indexOf Sylhet: 2
0: Rajshahi
1: Chattogram
2: Sylhet
List<String> cities = new ArrayList<>()creates an empty list of strings. The type in angle brackets is a generic parameter; the empty<>(diamond) lets Java infer it.- Declaring the variable as
Listrather thanArrayListis good practice: you can switch to another list type later without changing other code. add(x)appends;add(i, x)inserts and shifts later elements right.get(i)reads,set(i, x)replaces, and indexes start at 0. An index outside0tosize() - 1throwsIndexOutOfBoundsException.containsandindexOfsearch the list usingequals();indexOfreturns -1 if the item is missing.
Sorting, Removing and Immutable Lists
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> marks = new ArrayList<>(List.of(72, 95, 60, 88, 95));
Collections.sort(marks);
System.out.println("Sorted: " + marks);
marks.sort(Comparator.reverseOrder());
System.out.println("Descending: " + marks);
System.out.println("Max: " + Collections.max(marks) + ", frequency of 95: "
+ Collections.frequency(marks, 95));
// Removing while looping: use removeIf, not a for-each loop
marks.removeIf(m -> m < 70);
System.out.println("Passing: " + marks);
// remove(int) removes by index; remove(Object) removes by value
marks.remove(Integer.valueOf(88));
System.out.println("After removing 88: " + marks);
List<String> fixed = List.of("a", "b");
try {
fixed.add("c");
} catch (UnsupportedOperationException e) {
System.out.println("List.of() is immutable");
}
}
}
Output
Sorted: [60, 72, 88, 95, 95]
Descending: [95, 95, 88, 72, 60]
Max: 95, frequency of 95: 2
Passing: [95, 95, 88, 72]
After removing 88: [95, 95, 72]
List.of() is immutable
- Collections hold objects, not primitives, so a list of numbers is
List<Integer>. Java converts betweenintandIntegerautomatically (autoboxing). Collections.sort(list)sorts in natural order;list.sort(Comparator.reverseOrder())sorts descending.removeIftakes a lambda and removes every matching element safely. Removing inside a for-each loop throwsConcurrentModificationException.- For a
List<Integer>,remove(1)removes index 1. To remove the value, pass an object:remove(Integer.valueOf(88)). List.of(...)creates an unmodifiable list. Wrap it innew ArrayList<>(...)when you need to change it.
Array vs ArrayList vs LinkedList
| Array | ArrayList | LinkedList | |
|---|---|---|---|
| Size | Fixed | Grows automatically | Grows automatically |
| Holds primitives | Yes | No (wrapper types) | No |
get(i) | O(1) | O(1) | O(n) |
| Add at end | Not possible | O(1) on average | O(1) |
| Insert or remove in the middle | Manual | O(n), shifts elements | O(1) once positioned |
In practice ArrayList is faster than LinkedList for almost every workload because its elements sit next to each other in memory. See Java Arrays for fixed-size arrays.
Common Mistakes
- Using
intas the type:ArrayList<int>does not compile; useInteger. - Removing during a for-each loop; use
removeIfor anIterator. - Confusing
remove(int)withremove(Object)on integer lists. - Calling
addonList.of()orArrays.asList()results, which are fixed.
Practice Exercises
Exercise 1. Build a list of the numbers 1 to 10 and print only the odd ones.
Show answer
List<Integer> nums = new ArrayList<>();
for (int i = 1; i <= 10; i++) nums.add(i);
nums.removeIf(n -> n % 2 == 0);
System.out.println(nums); // [1, 3, 5, 7, 9]
Exercise 2. Sort a list of names by length, shortest first.
Show answer
List<String> names = new ArrayList<>(List.of("Tania", "Arif", "Nusrat"));
names.sort(Comparator.comparingInt(String::length));
System.out.println(names); // [Arif, Tania, Nusrat]
Frequently Asked Questions
How does ArrayList grow?
It stores elements in an internal array. When that array is full, it creates a larger one (about 1.5 times the size) and copies the elements across, which is why adding at the end is fast on average.
How do I convert between an array and an ArrayList?
Use new ArrayList<>(Arrays.asList(arr)) for an object array, and list.toArray(new String[0]) to go back.
Summary
ArrayListis a resizable, ordered list with fast index access.- Use
add,get,set,remove,sizeandcontains. - Sort with
Collections.sortorlist.sort(comparator). - Remove safely with
removeIf; rememberList.ofis unmodifiable.
Next: Java HashMap.
