Java ArrayList

Introduction

ArrayList in Java is a resizable array implementation of the List interface. Unlike arrays, ArrayList can grow and shrink dynamically, which makes it a flexible and convenient data structure for managing collections of objects. It is part of the java.util package and provides various methods to manipulate the elements in the list.

Table of Contents

  1. What is ArrayList
  2. Key Points About ArrayList
  3. Creating an ArrayList and Adding New Elements to It
  4. Creating an ArrayList from Another Collection
  5. Accessing Elements from an ArrayList
  6. Removing Elements from an ArrayList
  7. Iterating Over an ArrayList
  8. Searching for Elements in an ArrayList
  9. ArrayList of User-Defined Objects
  10. Sorting an ArrayList
  11. Synchronizing Access to an ArrayList
  12. All ArrayList Class Methods
  13. Conclusion

1. What is ArrayList?

An ArrayList is a dynamic array that can grow as needed to accommodate more elements. It implements the List interface and provides a wide range of methods to manage and manipulate collections of objects.

2. Key Points About ArrayList

  1. Resizable Array:
    • An ArrayList is a resizable array, also known as a dynamic array. It grows to accommodate new elements and shrinks when elements are removed.
  2. Internal Array Storage:
    • ArrayList internally uses an array to store elements. Similar to arrays, it allows you to retrieve elements by their index.
  3. Allows Duplicates and Null Values:
    • ArrayList permits duplicate elements and null values.
  4. Ordered Collection:
    • ArrayList is an ordered collection. It maintains the order of insertion of elements.
  5. Boxed Types for Primitives:
    • You cannot create an ArrayList of primitive types like int, char, etc. Instead, you need to use boxed types such as Integer, Character, Boolean, etc.
  6. Not Synchronized:
    • ArrayList is not synchronized. If multiple threads attempt to modify an ArrayList simultaneously, the outcome will be non-deterministic. You must explicitly synchronize access to an ArrayList if it is to be modified by multiple threads concurrently.

3. Creating an ArrayList and Adding New Elements to It

To create an ArrayList, you can use the ArrayList constructor. You can then use the add method to add elements to the list.

Example:

In this example, we create an ArrayList of strings and add a few elements to it.

import java.util.ArrayList;
import java.util.List;

public class ArrayListExample {
    public static void main(String[] args) {
        // Creating an ArrayList
        List<String> fruits = new ArrayList<>();

        // Adding new elements to the ArrayList
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");

        // Displaying the ArrayList
        System.out.println("ArrayList: " + fruits);
    }
}

Output:

ArrayList: [Apple, Banana, Cherry]

4. Creating an ArrayList from Another Collection

You can create an ArrayList from another collection by passing the collection to the ArrayList constructor.

Example:

In this example, we create a List of strings using List.of and then create an ArrayList from this collection.

import java.util.ArrayList;
import java.util.List;

public class ArrayListFromCollection {
    public static void main(String[] args) {
        // Creating a List
        List<String> fruits = List.of("Apple", "Banana", "Cherry");

        // Creating an ArrayList from another collection
        List<String> fruitList = new ArrayList<>(fruits);

        // Displaying the ArrayList
        System.out.println("ArrayList: " + fruitList);
    }
}

Output:

ArrayList: [Apple, Banana, Cherry]

5. Accessing Elements from an ArrayList

You can access elements from an ArrayList using various methods such as isEmpty, size, get, and set.

Example:

In this example, we demonstrate how to check if an ArrayList is empty, find its size, access an element at a particular index, and modify an element at a particular index.

import java.util.ArrayList;
import java.util.List;

public class AccessArrayList {
    public static void main(String[] args) {
        // Creating an ArrayList
        List<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");

        // Checking if the ArrayList is empty
        System.out.println("Is the ArrayList empty? " + fruits.isEmpty());

        // Finding the size of the ArrayList
        System.out.println("Size of the ArrayList: " + fruits.size());

        // Accessing the element at a particular index
        System.out.println("Element at index 1: " + fruits.get(1));

        // Modifying the element at a particular index
        fruits.set(1, "Blueberry");
        System.out.println("Updated ArrayList: " + fruits);
    }
}

Output:

Is the ArrayList empty? false
Size of the ArrayList: 3
Element at index 1: Banana
Updated ArrayList: [Apple, Blueberry, Cherry]

6. Removing Elements from an ArrayList

You can remove elements from an ArrayList using various methods such as remove(int index), remove(Object o), removeAll, removeIf, and clear.

Example:

In this example, we demonstrate how to remove elements from an ArrayList using different methods.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class RemoveElementsArrayList {
    public static void main(String[] args) {
        // Creating an ArrayList
        List<String> fruits = new ArrayList<>(Arrays.asList("Apple", "Banana", "Cherry", "Date", "Elderberry"));

        // Removing the element at a given index
        fruits.remove(1);
        System.out.println("After removing element at index 1: " + fruits);

        // Removing an element from the ArrayList
        fruits.remove("Cherry");
        System.out.println("After removing 'Cherry': " + fruits);

        // Removing all elements that exist in a given collection
        List<String> toRemove = Arrays.asList("Date", "Elderberry");
        fruits.removeAll(toRemove);
        System.out.println("After removing all elements in toRemove: " + fruits);

        // Removing all elements matching a given predicate
        fruits.removeIf(fruit -> fruit.startsWith("A"));
        System.out.println("After removing elements starting with 'A': " + fruits);

        // Clearing the ArrayList
        fruits.clear();
        System.out.println("After clearing the ArrayList: " + fruits);
    }
}

Output:

After removing element at index 1: [Apple, Cherry, Date, Elderberry]
After removing 'Cherry': [Apple, Date, Elderberry]
After removing all elements in toRemove: [Apple]
After removing elements starting with 'A': []
After clearing the ArrayList: []

7. Iterating Over an ArrayList

You can iterate over an ArrayList using various methods such as Java 8 forEach and lambda expressions, iterator, listIterator, simple for-each loop, and for loop with an index.

Example:

In this example, we demonstrate different ways to iterate over an ArrayList.

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

public class IterateArrayList {
    public static void main(String[] args) {
        // Creating an ArrayList
        List<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");

        // Using Java 8 forEach and lambda expression
        System.out.println("Using Java 8 forEach and lambda expression:");
        fruits.forEach(fruit -> System.out.println(fruit));

        // Using iterator
        System.out.println("Using iterator:");
        Iterator<String> iterator = fruits.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }

        // Using listIterator
        System.out.println("Using listIterator:");
        ListIterator<String> listIterator = fruits.listIterator();
        while (listIterator.hasNext()) {
            System.out.println(listIterator.next());
        }

        // Using simple for-each loop
        System.out.println("Using simple for-each loop:");
        for (String fruit : fruits) {
            System.out.println(fruit);
        }

        // Using for loop with index
        System.out.println("Using for loop with index:");
        for (int i = 0; i < fruits.size(); i++) {
            System.out.println(fruits.get(i));
        }
    }
}

Output:

Using Java 8 forEach and lambda expression:
Apple
Banana
Cherry
Using iterator:
Apple
Banana
Cherry
Using listIterator:
Apple
Banana
Cherry
Using simple for-each loop:
Apple
Banana
Cherry
Using for loop with index:
Apple
Banana
Cherry

8. Searching for Elements in an ArrayList

You can search for elements in an ArrayList using methods such as contains, indexOf, and lastIndexOf.

Example:

In this example, we demonstrate how to check if an ArrayList contains a given element, find the index of the first occurrence of an element, and find the index of the last occurrence of an element.

import java.util.ArrayList;
import java.util.List;

public class SearchArrayList {
    public static void main(String[] args) {
        // Creating an ArrayList
        List<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");
        fruits.add("Banana");

        // Check if the ArrayList contains a given element
        System.out.println("Does the ArrayList contain 'Banana'? " + fruits.contains("Banana"));

        // Find the index of the first occurrence of an element
        System.out.println("Index of the first occurrence of 'Banana': " + fruits.indexOf("Banana"));

        // Find the index of the last occurrence of an element
        System.out.println("Index of the last occurrence of 'Banana': " + fruits.lastIndexOf("Banana"));
    }
}

Output:

Does the ArrayList contain 'Banana'? true
Index of the first occurrence of 'Banana': 1
Index of the last occurrence of 'Banana': 3

9. ArrayList of User-Defined Objects

You can use ArrayList to store user-defined objects. This involves creating a class for the objects you want to store and then creating an ArrayList to manage these objects.

Example:

In this example, we create a Person class and then create an ArrayList to store Person objects.

import java.util.ArrayList;
import java.util.List;

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{name='" + name + "', age=" + age + "}";
    }
}

public class UserDefinedObjectArrayList {
    public static void main(String[] args) {
        // Creating an ArrayList of Person objects
        List<Person> people = new ArrayList<>();
        people.add(new Person("Alice", 30));
        people.add(new Person("Bob", 25));
        people.add(new Person("Charlie", 35));

        // Displaying the ArrayList
        System.out.println("ArrayList of Person objects: " + people);
    }
}

Output:

ArrayList of Person objects: [Person{name='Alice', age=30}, Person{name='Bob', age=25}, Person{name='Charlie', age=35}]

10. Sorting an ArrayList

You can sort an ArrayList using the Collections.sort method. If you want to sort a list of user-defined objects, the class should implement the Comparable interface or you should provide a Comparator.

Example:

In this example, we create a Person class that implements the Comparable interface to sort by age.

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

class Person implements Comparable<Person> {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public int compareTo(Person other) {
        return Integer.compare(this.age, other.age);
    }

    @Override
    public String toString() {
        return "Person{name='" + name + "', age=" + age + "}";
    }
}

public class SortArrayList {
    public static void main(String[] args) {
        // Creating an ArrayList of Person objects
        List<Person> people = new ArrayList<>();
        people.add(new Person("Alice", 30));
        people.add(new Person("Bob", 25));
        people.add(new Person("Charlie", 35));

        // Sorting the ArrayList
        Collections.sort(people);

        // Displaying the sorted ArrayList
        System.out.println("Sorted ArrayList: " + people);
    }
}

Output:

Sorted ArrayList: [Person{name='Bob', age=25}, Person{name='Alice', age=30}, Person{name='Charlie', age=35}]

11. Synchronizing Access to an ArrayList

ArrayList is not synchronized by default. If you need to use an ArrayList in a multi-threaded environment, you can synchronize it using Collections.synchronizedList.

Example:

In this example, we demonstrate how to synchronize an ArrayList.

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

public class SynchronizedArrayList {
    public static void main(String[] args) {
        // Creating an ArrayList
        List<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");

        // Synchronizing the ArrayList
        List<String> synchronizedFruits = Collections.synchronizedList(fruits);

        // Using synchronized block to iterate over the synchronized ArrayList
        synchronized (synchronizedFruits) {
            for (String fruit : synchronizedFruits) {
                System.out.println(fruit);
            }
        }
    }
}

Output:

Apple
Banana
Cherry

11. All ArrayList Class Methods

12. Conclusion

ArrayList is a versatile and powerful data structure in Java that provides dynamic array capabilities. It allows for fast, random access to elements, and its size can dynamically grow and shrink. Understanding how to create, manipulate, and iterate over ArrayList can help you effectively manage collections of objects in your Java applications. Additionally, knowing how to handle user-defined objects, sort, and synchronize access to ArrayList can further enhance your ability to work with this data structure in various scenarios.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top