ArrayList in Java

Java ArrayList: A Complete Guide with Examples and Exercises

The ArrayList class in Java is part of the java.util package and provides a dynamic array that can grow or shrink in size as needed. Unlike standard arrays, which have a fixed size, ArrayList allows you to store and manipulate data in a more flexible way. This guide will help you understand how to use the ArrayList class, explore its methods, and provide exercises to practice working with it.


Table of Contents

  1. Introduction to ArrayList
  2. Creating and Initializing ArrayList
  3. Commonly Used ArrayList Methods
  4. Iterating Over an ArrayList
  5. ArrayList vs Array
  6. Exercises

1. Introduction to ArrayList

An ArrayList in Java is a resizable array implementation of the List interface. It allows you to store elements dynamically and access them by their index position. The main advantages of using ArrayList over arrays are:

  • Dynamic Sizing: Unlike arrays, ArrayList can grow or shrink as elements are added or removed.
  • Index-Based Access: Elements in an ArrayList can be accessed using an index, similar to arrays.
  • Built-in Methods: ArrayList comes with many useful methods for adding, removing, and manipulating elements.

Key Features of ArrayList:

  • It allows duplicates.
  • It maintains the order of insertion.
  • It is not synchronized (i.e., not thread-safe).
  • It can contain elements of any type, but it is typically used with generic types.

2. Creating and Initializing ArrayList

You can create an ArrayList in a variety of ways. The most common method is using the default constructor, or by initializing it with an initial capacity.

Example 1: Creating an Empty ArrayList

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        // Create an empty ArrayList of Strings
        ArrayList<String> names = new ArrayList<>();

        // Adding elements to the ArrayList
        names.add("Alice");
        names.add("Bob");
        names.add("Charlie");

        // Printing the ArrayList
        System.out.println(names);
    }
}

Example 2: Creating an ArrayList with Initial Capacity

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        // Create an ArrayList with an initial capacity of 5
        ArrayList<Integer> numbers = new ArrayList<>(5);

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

        System.out.println(numbers);
    }
}

Example 3: Creating and Initializing an ArrayList with Elements

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        // Create and initialize an ArrayList with elements
        ArrayList<String> fruits = new ArrayList<>(List.of("Apple", "Banana", "Cherry"));
        System.out.println(fruits);
    }
}

3. Commonly Used ArrayList Methods

ArrayList comes with several methods to manipulate the elements it contains. Here are some commonly used methods:

  • add(E e): Adds an element to the end of the list.
  • get(int index): Retrieves an element at the specified index.
  • remove(int index): Removes the element at the specified index.
  • remove(Object o): Removes the first occurrence of the specified element.
  • size(): Returns the number of elements in the list.
  • contains(Object o): Checks if the list contains the specified element.
  • set(int index, E element): Replaces the element at the specified index with the given element.
  • clear(): Removes all elements from the list.

Example: Using ArrayList Methods

import java.util.ArrayList;

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

        // Add elements to the ArrayList
        colors.add("Red");
        colors.add("Green");
        colors.add("Blue");

        // Get an element at index 1
        System.out.println("Element at index 1: " + colors.get(1));  // Green

        // Remove element at index 0
        colors.remove(0);  // Removes "Red"

        // Set a new value at index 1
        colors.set(1, "Yellow");

        // Check if an element exists
        boolean containsBlue = colors.contains("Blue");  // true
        System.out.println("Contains Blue? " + containsBlue);

        // Print the final ArrayList
        System.out.println(colors);
    }
}

4. Iterating Over an ArrayList

There are several ways to iterate over the elements of an ArrayList:

Example 1: Using a for Loop

import java.util.ArrayList;

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

        // Iterate using a for loop
        for (int i = 0; i < names.size(); i++) {
            System.out.println(names.get(i));
        }
    }
}

Example 2: Using a for-each Loop

import java.util.ArrayList;

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

        // Iterate using a for-each loop
        for (String name : names) {
            System.out.println(name);
        }
    }
}

Example 3: Using Java 8 forEach Method

import java.util.ArrayList;

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

        // Iterate using forEach method
        names.forEach(name -> System.out.println(name));
    }
}

5. ArrayList vs Array

Both arrays and ArrayList are used to store multiple values, but they have key differences:

  • Size: Arrays have a fixed size, whereas ArrayList can grow or shrink dynamically.
  • Type: Arrays can hold elements of any type, while ArrayList is typically used with a single type (generic type).
  • Performance: Arrays are faster than ArrayList when working with a known size. However, ArrayList is more flexible when dealing with dynamic data.
  • Memory Usage: ArrayList uses more memory than an array because of its dynamic resizing feature.

Example: Comparing Array and ArrayList

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        // Using an array
        int[] arr = new int[3];
        arr[0] = 10;
        arr[1] = 20;
        arr[2] = 30;
        System.out.println("Array: " + arr[0] + ", " + arr[1] + ", " + arr[2]);

        // Using an ArrayList
        ArrayList<Integer> list = new ArrayList<>();
        list.add(10);
        list.add(20);
        list.add(30);
        System.out.println("ArrayList: " + list);
    }
}

6. Exercises

Exercise 1: Add and Remove Elements

Write a program that:

  1. Creates an ArrayList of integers.
  2. Adds 5 numbers to the list.
  3. Removes the second number.
  4. Prints the resulting list.

Exercise 2: Search for an Element

Write a program that:

  1. Creates an ArrayList of string names.
  2. Checks if a specific name exists in the list and prints a corresponding message.

Exercise 3: Reverse an ArrayList

Write a program that:

  1. Creates an ArrayList of integers.
  2. Reverses the list and prints it.

Exercise 4: Find Maximum Element

Write a program that:

  1. Creates an ArrayList of integers.
  2. Finds and prints the largest number in the list.

Solution for Exercise 1

import java.util.ArrayList;

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

        // Adding numbers
        numbers.add(10);
        numbers.add(20);
        numbers.add(30);
        numbers.add(40);
        numbers.add(50);

        // Removing the second number (index 1)
        numbers.remove(1);

        // Print the resulting list
        System.out.println(numbers);
    }
}

Solution for Exercise 2

import java.util.ArrayList;

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

        // Adding names
        names.add("Alice");
        names.add("Bob");
        names.add("Charlie");

        // Check if a specific name exists
        if (names.contains("Bob")) {
            System.out.println("Bob is in the list.");
        } else {
            System.out.println("Bob is not in the list.");
        }
    }
}

Conclusion

The `

ArrayListclass in Java provides a flexible and dynamic way to store and manipulate a collection of elements. It is one of the most commonly used classes in thejava.utilpackage because of its dynamic sizing and built-in methods for adding, removing, and manipulating elements. By practicing the exercises in this guide, you will gain a better understanding of how to work withArrayList` in Java and make use of its features in your programs.

Leave a Comment

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

Scroll to Top