Java ArrayList


Java ArrayList is one of the most popular and useful classes in the Java Collections Framework. It provides a dynamic way to store data, similar to arrays, but with more flexibility. Unlike arrays, which have a fixed size, an ArrayList can automatically increase or decrease its size when elements are added or removed.

ArrayList is mainly used when you need a resizable data structure that allows easy insertion, deletion, and access to elements.

What is an ArrayList in Java

An ArrayList in Java is a class that implements the List interface from the java.util package. It uses a dynamic array internally to store the elements. When the array reaches its capacity, it creates a new one with a larger size and copies all existing elements into it.

ArrayList maintains the order of insertion, allows duplicate elements, and supports random access using indexes. This makes it more flexible than arrays, especially when working with data that frequently changes in size.

How to Create an ArrayList in Java

Before using an ArrayList, you need to import it from the java.util package. Then, you can create an instance using the new keyword.

Syntax

import java.util.ArrayList;

public class Example {
    public static void main(String[] args) {
        ArrayList<String> names = new ArrayList<String>();
        names.add("Aisha");
        names.add("Meera");
        names.add("Priya");
        System.out.println(names);
    }
}

In this example, the ArrayList named names stores string values. The add() method is used to insert elements into the list.

Important Features of ArrayList

  • It grows automatically when elements are added.

  • It allows duplicate values.

  • It maintains insertion order.

  • It provides random access using indexes.

  • It allows null values.

  • It is slower for insertions and deletions in the middle of the list because it shifts elements.

Adding Elements to an ArrayList

You can use the add() method to insert new elements. The method can be used in two ways — to add elements at the end or at a specific index.

ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.add(1, 15); // insert 15 at index 1
System.out.println(numbers);

Here, the element 15 is inserted at index 1, shifting the other elements.

Accessing Elements from an ArrayList

To access an element, use the get() method with the element’s index position.

String firstName = names.get(0);
System.out.println("First Name: " + firstName);

The index starts from 0, so the first element is at index 0.

Updating Elements in an ArrayList

If you want to change an existing element, use the set() method.

names.set(1, "Riya");
System.out.println(names);

This replaces the element at index 1 with “Riya”.

Removing Elements from an ArrayList

You can remove an element either by specifying the value or the index.

names.remove("Priya"); // removes by value
names.remove(0);       // removes by index
System.out.println(names);

When you remove an element, the size of the ArrayList decreases automatically.

Looping Through an ArrayList

You can loop through an ArrayList in different ways. Here are the most common ones:

Using a For Loop

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

Using a For-Each Loop

for(String n : names) {
    System.out.println(n);
}

Using an Iterator

import java.util.Iterator;

Iterator<String> it = names.iterator();
while(it.hasNext()) {
    System.out.println(it.next());
}

Common Methods of ArrayList

Method Description
add() Adds an element to the list
get() Returns the element at a specific index
set() Updates an element at a given index
remove() Deletes an element from the list
size() Returns the total number of elements
clear() Removes all elements from the list
contains() Checks if an element exists
isEmpty() Checks if the list is empty

Difference Between Array and ArrayList

Feature Array ArrayList
Size Fixed Dynamic
Data Type Can store primitives Stores only objects
Performance Faster for access Slower due to resizing
Memory Static Resizable
Flexibility Less flexible More flexible

Arrays are best when you know the exact number of elements in advance. ArrayLists are preferred when the size of data changes frequently.

Example Program of ArrayList

import java.util.ArrayList;

public class ArrayListExample {
    public static void main(String[] args) {
        ArrayList<String> colors = new ArrayList<String>();
        colors.add("Red");
        colors.add("Green");
        colors.add("Blue");
        System.out.println("Colors: " + colors);

        colors.remove("Green");
        colors.add("Yellow");
        System.out.println("Updated Colors: " + colors);

        for(String c : colors) {
            System.out.println(c);
        }
    }
}

This program creates an ArrayList of colors, removes one element, adds a new one, and prints all elements using a for-each loop.

When to Use ArrayList

You should use ArrayList when:

  • The number of elements changes frequently.

  • You need to access elements quickly.

  • You don’t need to insert or remove items from the middle too often.

If you frequently insert or delete elements in between, a LinkedList might be a better option.

Summary of the Tutorial

ArrayList in Java is a powerful and flexible data structure that allows dynamic resizing and easy data manipulation. It supports duplicate elements, maintains order, and provides several built-in methods for common operations. While it may not be as fast as arrays for fixed data, its dynamic behavior and convenience make it ideal for most real-world Java applications.


Practice Questions

  1. Create an ArrayList of integers and display the sum of all elements.

  2. Write a Java program to find the maximum and minimum values in an ArrayList.

  3. Create an ArrayList of strings and remove all duplicate elements.

  4. Write a program to check if a particular element exists in an ArrayList.

  5. Create an ArrayList of names and sort them alphabetically.

  6. Write a program to reverse the order of elements in an ArrayList without using built-in reverse methods.

  7. Create two ArrayLists and merge them into one.

  8. Write a Java program that removes all even numbers from an ArrayList of integers.

  9. Convert an ArrayList into a normal array and display all elements.

  10. Write a program to find the frequency of each element in an ArrayList.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top