Skip to main content

ArrayList

What is an ArrayList?

An ArrayList is a resizable array-like structure that belongs to the Java Collections Framework. It implements the List interface, providing dynamic resizing, easy insertion, and removal of elements. Unlike arrays, ArrayLists can grow or shrink in size during runtime.

Declaration and Initialization:

1. Declaration:

To use an ArrayList, you need to import it from the java.util package:

import java.util.ArrayList;

Then, declare an ArrayList:

// Declare an ArrayList of integers
ArrayList<Integer> numbers;

2. Initialization:

Initialize an ArrayList using the new keyword:

// Initialize an ArrayList of integers
numbers = new ArrayList<>();

Combine declaration and initialization in a single line:

// Declare and initialize an ArrayList of integers
ArrayList<Integer> numbers = new ArrayList<>();

Adding Elements to an ArrayList:

You can add elements to an ArrayList using the add method:

// Add elements to the ArrayList
numbers.add(1);
numbers.add(2);
numbers.add(3);

Accessing Elements:

Access elements using their index, similar to arrays:

// Accessing the first element
int firstElement = numbers.get(0);

Common Operations:

1. Iterating Through an ArrayList:

Use a for-each loop to iterate through the elements of an ArrayList:

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

2. Finding the Size of an ArrayList:

The size method provides the number of elements in an ArrayList:

int arrayListSize = numbers.size();

3. Updating ArrayList Elements:

You can update the value of an element by using the set method:

numbers.set(2, 10);

4. Removing Elements:

Remove elements by value or index using the remove method:

numbers.remove(Integer.valueOf(2)); // Remove by value
numbers.remove(0); // Remove by index

Example: Calculating the Sum of ArrayList Elements:

Let's create a simple program that calculates the sum of elements in an ArrayList:

import java.util.ArrayList;

public class ArrayListSum {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);

// Calculate the sum
int sum = 0;
for (int number : numbers) {
sum += number;
}

// Print the result
System.out.println("Sum of elements: " + sum);
}
}
tip

Be mindful of the dynamic resizing nature of ArrayList. Preallocate its size if the number of elements is known in advance to optimize memory usage.

Challenge Question

Compare the performance characteristics of ArrayList and arrays in terms of insertion, deletion, and access times. In what scenarios would you choose one over the other?