Skip to main content
Documents
Share
LinkedIn
Facebook
Twitter
Copy
Java keywordsIntroduction To JavaJava File HandlingJava Language BasicsJava ArraysJava Object-Oriented Programming

Java ArrayList

The ArrayList in Java is a part of the Java Collections Framework and is found in the java.util package. It is a resizable array implementation of the List interface, providing a convenient way to store dynamically sized collections of elements.

Usage

ArrayList is used when you need a flexible array that can grow and shrink in size. It allows for fast random access and is suitable for scenarios where frequent read operations are required.

Syntax

ArrayList<Type> arrayListName = new ArrayList<Type>();
  • Type: The type of elements in the list.
  • arrayListName: The name of the ArrayList instance.

Examples

Example 1: Basic Operations

import java.util.ArrayList;

public class BasicArrayListExample {
    public static void main(String[] args) {
        ArrayList<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Orange");

        System.out.println("Fruits: " + fruits);

        fruits.remove("Banana");
        System.out.println("After removal: " + fruits);

        System.out.println("First fruit: " + fruits.get(0));
    }
}

In this example, an ArrayList of String type is created to store fruit names. The add() method is used to insert elements, remove() deletes an element, and get() retrieves an element by its index.

Example 2: Iterating Over an ArrayList

import java.util.ArrayList;

public class IterateArrayListExample {
    public static void main(String[] args) {
        ArrayList<Integer> numbers = new ArrayList<>();
        numbers.add(10);
        numbers.add(20);
        numbers.add(30);

        for (int number : numbers) {
            System.out.println(number);
        }
    }
}

This example demonstrates how to iterate over an ArrayList using a for-each loop. An ArrayList of Integer type is created, and each element is printed to the console.

Example 3: Sorting an ArrayList

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

public class SortArrayListExample {
    public static void main(String[] args) {
        ArrayList<String> names = new ArrayList<>();
        names.add("John");
        names.add("Alice");
        names.add("Bob");

        Collections.sort(names);

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

In this example, an ArrayList of String type is sorted using the Collections.sort() method, which arranges the elements in natural order.

Additional Operations

The ArrayList class provides several methods for performing operations on the elements:

  • Accessing Items: Use the get() method to retrieve elements by index.
  • Modifying Items: Use the set() method to change an element at a specific index.
  • Removing Items: Use the remove() method to delete an element by index, and the clear() method to remove all elements.
  • Getting ArrayList Size: Use the size() method to find the number of elements in the ArrayList.
  • Using Other Types: Store different data types in ArrayList using wrapper classes for primitive types (e.g., Integer, Boolean).

Tips and Best Practices

  • Initial Capacity: If the size of the ArrayList is known in advance, specify an initial capacity to improve performance and reduce the need for resizing.
    ArrayList<String> list = new ArrayList<>(50); // Initial capacity of 50
  • Type Safety: Use generics to ensure type safety and avoid runtime errors.
    ArrayList<Integer> numbers = new ArrayList<>(); // Type-safe declaration
  • Avoid Frequent Resizing: Minimize frequent additions and removals of elements to reduce the overhead of resizing operations.
  • Use Iterator for Safe Removal: When removing elements during iteration, use an Iterator to avoid ConcurrentModificationException.
    Iterator<String> iterator = list.iterator();
    while (iterator.hasNext()) {
        if (condition) {
            iterator.remove();
        }
    }
  • Consider LinkedList for Frequent Insertions/Deletions: If frequent insertions and deletions are needed, consider using LinkedList, which provides better performance for such operations.