ArrayList

ArrayList is one of the most commonly used classes in the Java Collections Framework. It provides a dynamic array that can grow or shrink automatically as elements are added or removed. Unlike traditional arrays, an ArrayList does not require a fixed size, making it more flexible and easier to use in real-world applications.

ArrayList is widely used in Java applications, Android development, web applications, enterprise systems, and data management software. Understanding ArrayList is essential for working with collections of data efficiently.

What is ArrayList in Java?

ArrayList is a resizable array implementation provided by the Java Collections Framework.

It belongs to the:

java.util

package.

Unlike normal arrays, an ArrayList can automatically increase or decrease its size during program execution.

Example:

ArrayList<String> names = new ArrayList<>();

This creates an ArrayList that can store multiple String values.

Why Use ArrayList?

Traditional arrays have a fixed size.

Example:

String[] names = new String[5];

Once created, the size cannot be changed.

ArrayList solves this limitation by providing dynamic storage.

Benefits include:

  • Dynamic resizing
  • Easy insertion and deletion
  • Built-in methods
  • Better flexibility
  • Efficient data management
  • Integration with Java Collections Framework

Importing ArrayList

Before using ArrayList, import the class:

import java.util.ArrayList;

This gives access to all ArrayList features.

Creating an ArrayList

Empty ArrayList

ArrayList<String> names = new ArrayList<>();

ArrayList of Integers

ArrayList<Integer> numbers = new ArrayList<>();

ArrayList of Doubles

ArrayList<Double> prices = new ArrayList<>();

ArrayList can store different data types using wrapper classes.

Adding Elements

The add() method inserts elements into the ArrayList.

Example:

ArrayList<String> names = new ArrayList<>();

names.add("Ali");
names.add("Ahmed");
names.add("Sara");

System.out.println(names);

Output:

[Ali, Ahmed, Sara]

Elements are added at the end of the list.

Accessing Elements

The get() method retrieves an element by index.

Example:

ArrayList<String> names = new ArrayList<>();

names.add("Ali");
names.add("Ahmed");

System.out.println(names.get(0));

Output:

Ali

ArrayList indexing starts from 0.

Updating Elements

The set() method modifies an existing element.

Example:

ArrayList<String> names = new ArrayList<>();

names.add("Ali");
names.add("Ahmed");

names.set(1, "Sara");

System.out.println(names);

Output:

[Ali, Sara]

The value at index 1 is replaced.

Removing Elements

The remove() method deletes an element.

Example:

ArrayList<String> names = new ArrayList<>();

names.add("Ali");
names.add("Ahmed");

names.remove(0);

System.out.println(names);

Output:

[Ahmed]

Elements shift automatically after removal.

Finding ArrayList Size

The size() method returns the number of elements.

Example:

ArrayList<String> names = new ArrayList<>();

names.add("Ali");
names.add("Sara");

System.out.println(names.size());

Output:

2

This method is useful for loops and validations.

Checking if an Element Exists

The contains() method checks whether an element is present.

Example:

ArrayList<String> names = new ArrayList<>();

names.add("Ali");

System.out.println(names.contains("Ali"));

Output:

true

This method helps validate data efficiently.

Clearing All Elements

The clear() method removes all elements.

Example:

ArrayList<String> names = new ArrayList<>();

names.add("Ali");
names.add("Sara");

names.clear();

System.out.println(names);

Output:

[]

The ArrayList becomes empty.

Looping Through an ArrayList

Using For Loop

Example:

ArrayList<String> names = new ArrayList<>();

names.add("Ali");
names.add("Ahmed");
names.add("Sara");

for (int i = 0; i < names.size(); i++) {

    System.out.println(names.get(i));

}

Output:

Ali
Ahmed
Sara

Using Enhanced For Loop

Example:

for (String name : names) {

    System.out.println(name);

}

This approach is simpler and more readable.

ArrayList of Numbers

Example:

ArrayList<Integer> numbers = new ArrayList<>();

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

for (Integer number : numbers) {

    System.out.println(number);

}

Output:

10
20
30

ArrayList can efficiently store and process numeric values.

Sorting an ArrayList

The Collections.sort() method sorts elements.

Example:

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

ArrayList<Integer> numbers = new ArrayList<>();

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

Collections.sort(numbers);

System.out.println(numbers);

Output:

[10, 20, 30]

Sorting is commonly used in data management applications.

Complete Example

import java.util.ArrayList;

public class Main {

    public static void main(String[] args) {

        ArrayList<String> students = new ArrayList<>();

        students.add("Ali");
        students.add("Ahmed");
        students.add("Sara");

        System.out.println("Total Students: " + students.size());

        for (String student : students) {

            System.out.println(student);

        }

    }

}

Output:

Total Students: 3
Ali
Ahmed
Sara

This demonstrates practical ArrayList usage.

Array vs ArrayList

FeatureArrayArrayList
SizeFixedDynamic
Built-in MethodsLimitedMany
Add/Remove ElementsDifficultEasy
PerformanceFaster for fixed dataMore flexible
Memory ManagementManualAutomatic

Arrays are useful for fixed-size data, while ArrayList is better for dynamic data.

Common ArrayList Methods

MethodPurpose
add()Add element
get()Retrieve element
set()Update element
remove()Delete element
size()Get total elements
contains()Check existence
clear()Remove all elements
isEmpty()Check if list is empty

These methods simplify data management.

Applications of ArrayList

ArrayList is widely used in:

  • Android applications
  • Student management systems
  • E-commerce platforms
  • Banking software
  • Inventory systems
  • Contact management applications
  • Online booking systems
  • Enterprise software

Most modern Java applications use ArrayList for dynamic data storage.

Common Beginner Mistakes

Forgetting to Import ArrayList

Incorrect:

ArrayList<String> names = new ArrayList<>();

Without:

import java.util.ArrayList;

the program will not compile.

Using Primitive Data Types

Incorrect:

ArrayList<int> numbers;

Correct:

ArrayList<Integer> numbers;

ArrayList requires wrapper classes.

Accessing Invalid Indexes

Incorrect:

names.get(5);

If index 5 does not exist, an exception occurs.

Confusing size() with length

Arrays use:

array.length

ArrayList uses:

list.size()

Understanding this difference is important.

Best Practices

When working with ArrayList:

  • Use generics for type safety
  • Check list size before accessing indexes
  • Use enhanced for loops when possible
  • Remove unnecessary elements to save memory
  • Choose ArrayList when dynamic sizing is needed
  • Use meaningful variable names

These practices improve code quality and maintainability.

Importance of ArrayList

ArrayList is important because it:

  • Stores dynamic collections of data
  • Simplifies data management
  • Provides powerful built-in methods
  • Improves development speed
  • Supports scalable applications
  • Integrates with the Collections Framework

It is one of the most valuable data structures in Java programming.

Conclusion

ArrayList is a dynamic and flexible collection class in Java that allows developers to store, manage, and manipulate groups of data efficiently. With features such as automatic resizing, built-in methods, and easy element management, ArrayList is widely used in Java, Android, and enterprise application development. Mastering ArrayList is an important step toward becoming a skilled Java developer and working effectively with collections of data.

Home » Intermediate Java > Strings and Collections > ArrayList