Reading history

Java ArrayList: add, get, set, remove and Sort

5 min read 0 views

Learn Java ArrayList with examples: creating lists, add, get, set, remove, contains, sorting with comparators, removeIf, List.of and ArrayList vs array vs LinkedList.

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 ArrayList with generics
  • add, get, set, remove and size
  • Searching with contains and indexOf
  • Sorting with Collections.sort and comparators
  • Safe removal with removeIf and 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 List rather than ArrayList is 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 outside 0 to size() - 1 throws IndexOutOfBoundsException.
  • contains and indexOf search the list using equals(); indexOf returns -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 between int and Integer automatically (autoboxing).
  • Collections.sort(list) sorts in natural order; list.sort(Comparator.reverseOrder()) sorts descending.
  • removeIf takes a lambda and removes every matching element safely. Removing inside a for-each loop throws ConcurrentModificationException.
  • 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 in new ArrayList<>(...) when you need to change it.

Array vs ArrayList vs LinkedList

ArrayArrayListLinkedList
SizeFixedGrows automaticallyGrows automatically
Holds primitivesYesNo (wrapper types)No
get(i)O(1)O(1)O(n)
Add at endNot possibleO(1) on averageO(1)
Insert or remove in the middleManualO(n), shifts elementsO(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

  1. Using int as the type: ArrayList<int> does not compile; use Integer.
  2. Removing during a for-each loop; use removeIf or an Iterator.
  3. Confusing remove(int) with remove(Object) on integer lists.
  4. Calling add on List.of() or Arrays.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

  • ArrayList is a resizable, ordered list with fast index access.
  • Use add, get, set, remove, size and contains.
  • Sort with Collections.sort or list.sort(comparator).
  • Remove safely with removeIf; remember List.of is unmodifiable.

Next: Java HashMap.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *