Lesson 50 of 50 – Java ArrayList
100%

Java ArrayList

An ArrayList is a resizable collection in Java. Unlike a normal array, an ArrayList can grow or shrink when elements are added or removed. It belongs to the Java Collections Framework and implements the List interface.

1. Introduction to ArrayList

A normal array has a fixed length after it is created.

String[] names = {"Rahul", "Amit", "Priya"};

An ArrayList can change its size as needed. It is useful when the number of elements may change while the program is running.

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> names = new ArrayList<>();

        names.add("Rahul");
        names.add("Amit");
        names.add("Priya");

        System.out.println(names);
    }
}

Output:

[Rahul, Amit, Priya]

2. Creating an ArrayList

First, import the ArrayList class from java.util.

import java.util.ArrayList;

ArrayList<String> students = new ArrayList<>();
ArrayList<Integer> numbers = new ArrayList<>();
ArrayList<Double> prices = new ArrayList<>();

Examples of generic types:

  • String stores text.
  • Integer stores integer values.
  • Double stores decimal values.
  • Character stores characters.
Remember: ArrayList uses objects as its element types. Use wrapper classes such as Integer instead of primitive types such as int.

3. Adding Elements Using add()

The add() method adds an element to the end of an ArrayList.

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> fruits = new ArrayList<>();

        fruits.add("Apple");
        fruits.add("Mango");
        fruits.add("Banana");
        fruits.add("Orange");

        System.out.println(fruits);
    }
}

Output:

[Apple, Mango, Banana, Orange]

You can also insert an element at a particular index using add(index, element).

fruits.add(1, "Grapes");

System.out.println(fruits);

Output:

[Apple, Grapes, Mango, Banana, Orange]

4. Accessing Elements Using get()

Use get(index) to retrieve an element from an ArrayList.

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> colors = new ArrayList<>();

        colors.add("Red");
        colors.add("Green");
        colors.add("Blue");

        System.out.println(colors.get(0));
        System.out.println(colors.get(1));
        System.out.println(colors.get(2));
    }
}

Output:

Red
Green
Blue

ArrayList indexing starts at zero. The first element is at index 0, and the second is at index 1.

Accessing an index outside the valid range causes an IndexOutOfBoundsException.

5. Updating Elements Using set()

The set() method replaces an existing element at a specified index.

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> fruits = new ArrayList<>();

        fruits.add("Apple");
        fruits.add("Mango");
        fruits.add("Banana");

        fruits.set(1, "Orange");

        System.out.println(fruits);
    }
}

Output:

[Apple, Orange, Banana]

The element at index 1 changes from Mango to Orange. The list size remains unchanged.

6. Removing Elements

Use remove() to delete an element from an ArrayList.

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> fruits = new ArrayList<>();

        fruits.add("Apple");
        fruits.add("Mango");
        fruits.add("Banana");

        fruits.remove(1);

        System.out.println(fruits);
    }
}

Output:

[Apple, Banana]

You can remove by index or by object value:

fruits.remove(0);          // Removes element at index 0
fruits.remove("Banana");   // Removes the matching object

For an ArrayList of integers, use remove(Integer.valueOf(20)) to remove the value 20 rather than the element at index 20.

7. Finding the Size of an ArrayList

The size() method returns the current number of elements.

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> names = new ArrayList<>();

        names.add("Rahul");
        names.add("Amit");
        names.add("Priya");

        System.out.println("Total names: " + names.size());
    }
}

Output:

Total names: 3

Unlike the fixed length of an array, the size of an ArrayList changes when elements are added or removed.

8. Looping Through an ArrayList

Use a for loop to access elements by index.

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> subjects = new ArrayList<>();

        subjects.add("Java");
        subjects.add("Python");
        subjects.add("HTML");

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

Output:

Java
Python
HTML

You can also use a for-each loop:

for (String subject : subjects) {
    System.out.println(subject);
}

A for-each loop is usually simpler when you only need to read each element.

9. Searching with contains() and indexOf()

Use contains() to check whether a value exists in the list. Use indexOf() to find the index of its first occurrence.

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> names = new ArrayList<>();

        names.add("Rahul");
        names.add("Amit");
        names.add("Priya");

        System.out.println(names.contains("Amit"));
        System.out.println(names.indexOf("Priya"));
        System.out.println(names.indexOf("Neha"));
    }
}

Output:

true
2
-1

The indexOf() method returns -1 when the specified element is not found.

10. Sorting an ArrayList

Use Collections.sort() to sort an ArrayList into natural order.

import java.util.ArrayList;
import java.util.Collections;

public class Main {
    public static void main(String[] args) {
        ArrayList<Integer> numbers = new ArrayList<>();

        numbers.add(40);
        numbers.add(10);
        numbers.add(30);
        numbers.add(20);

        Collections.sort(numbers);

        System.out.println(numbers);
    }
}

Output:

[10, 20, 30, 40]

For descending order, use:

Collections.sort(numbers, Collections.reverseOrder());

System.out.println(numbers);

Output:

[40, 30, 20, 10]

11. ArrayList of Numbers

ArrayList can store numeric wrapper objects such as Integer and Double.

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<Integer> marks = new ArrayList<>();

        marks.add(75);
        marks.add(80);
        marks.add(90);

        int total = 0;

        for (int mark : marks) {
            total += mark;
        }

        double average = (double) total / marks.size();

        System.out.println("Total Marks: " + total);
        System.out.println("Average Marks: " + average);
    }
}

Output:

Total Marks: 245
Average Marks: 81.66666666666667

Java automatically converts between int values and Integer objects in common assignment and method-call situations. This is called autoboxing and unboxing.

12. Common ArrayList Methods

Method Purpose
add(element) Adds an element.
add(index, element) Inserts an element at an index.
get(index) Returns an element.
set(index, element) Replaces an element.
remove(index) Removes the element at an index.
size() Returns the number of elements.
contains(element) Checks whether an element exists.
indexOf(element) Returns the first matching index or -1.
isEmpty() Checks whether the list is empty.
clear() Removes all elements.

13. Practice Assignments

  1. Create an ArrayList containing five student names.
  2. Add a new fruit to an ArrayList and display the list.
  3. Insert an element at index 2.
  4. Update an existing element using set().
  5. Remove an element by index and by value.
  6. Display the number of elements using size().
  7. Search for a student's name using contains().
  8. Sort a list of integers in ascending order.
  9. Calculate the total and average of five marks.
  10. Display all elements using both a for loop and a for-each loop.

🧠 Quick Quiz

1. Which method adds an element to an ArrayList?




2. Which method returns the number of elements in an ArrayList?




3. Which method replaces an element at a specified index?