Working with ArrayList: Essential Methods for Dynamic Collections

Core ArrayList Methods

Adding Elements

The add(E e) method appends an element to the end of the list.

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

boolean flag = names.add("Alice");
names.add("Bob");
names.add("Charlie");
names.add("David");

System.out.println(names);

Removing Elements

Two removal options exist: remove(Object o) deletes by value, while remove(int index) removes by position.

boolean deleted = names.remove("Alice");
System.out.println(deleted);

boolean missing = names.remove("Zara"); // returns false when element not found
System.out.println(missing);

String extracted = names.remove(1); // removes element at index 1
System.out.println(extracted);
System.out.println(names);

Updating Elements

The set(int index, E element) method replaces the element at the specified position.

String previous = names.set(0, "Eve"); // returns the old element
System.out.println(previous);
System.out.println(names);

Accessing Elements

The get(int index) method retrieves the element at the speicfied position.

String first = names.get(0);
System.out.println(first);

Determining Size

The size() method returns the number of elements in the list.

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

Complete Example

import java.util.ArrayList;

public class ArrayListDemo {
    public static void main(String[] args) {
        ArrayList<String> names = new ArrayList<>();
        
        names.add("Alice");
        names.add("Bob");
        names.add("Charlie");
        names.add("David");
        System.out.println("Initial list: " + names);
        
        names.remove("Bob");
        System.out.println("After removing Bob: " + names);
        
        String removed = names.remove(1);
        System.out.println("Removed element: " + removed);
        System.out.println("Current state: " + names);
        
        String old = names.set(0, "Eve");
        System.out.println("Replaced '" + old + "' with 'Eve'");
        
        System.out.println("Element at index 0: " + names.get(0));
        
        System.out.println("\nIterating through collection:");
        for (int i = 0; i < names.size(); i++) {
            System.out.println("  [" + i + "] " + names.get(i));
        }
    }
}

Output:

Initial list: [Alice, Bob, Charlie, David]
After removing Bob: [Alice, Charlie, David]
Removed element: Charlie
Current state: [Alice, David]
Replaced 'Alice' with 'Eve'
Element at index 0: Eve

Iterating through collection:
  [0] Eve
  [1] David

Tags: java ArrayList Collection Data Structures

Posted on Thu, 01 Oct 2026 16:55:14 +0000 by rachelkoh