Java ProgramsCollectionsArrayList Basic Operations

ArrayList Basic Operations in Java

beginner·  Collections  ·  List

Problem

ArrayList is backed by a resizable array, so every element has a numeric index that can be read or replaced directly, alongside adding new elements to the end.

Build an ArrayList of numbers, replace one element by index, then read another element and the list's size.

Input
add(10), add(20), add(30), set(1, 25)
Output
Element at index 2: 30

Java Program

Java
import java.util.ArrayList; public class ArrayListOperations { public static void main(String[] args) { ArrayList<Integer> numbers = new ArrayList<>(); numbers.add(10); numbers.add(20); numbers.add(30); numbers.set(1, 25); // replaces the element at index 1, in place System.out.println("Element at index 2: " + numbers.get(2)); System.out.println("List: " + numbers); System.out.println("Size: " + numbers.size()); } }

Output

Element at index 2: 30 List: [10, 25, 30] Size: 3

Core Logic

Adding three numbers builds the list, then set() replaces one of them by position before get() and size() read the result back.

How It Works
  1. 1add(10), add(20), add(30) each append one value, building the list [10, 20, 30].
  2. 2set(1, 25) replaces the element at index 1 — the value 20 — with 25, without changing the list's length.
  3. 3get(2) reads the value currently at index 2, which is still 30 since only index 1 changed.
  4. 4size() reports how many elements the list holds, unaffected by set() since it replaces rather than adds.
After set(1, 25), the list reads [10, 25, 30]get(2) returns 30 and size() returns 3.
💡

Key Point: set(index, value) requires that index to already exist — calling it beyond the current size throws IndexOutOfBoundsException rather than growing the list the way add() would.

Complexity
Time Complexity: O(1)Space Complexity: O(1)

Why: ArrayList is backed by an array, so add() (amortized), get(), and set() all reach their target slot directly without shifting any other elements.

Key Concepts

ArrayListget()set()size()

Related Programs