← Back
CreatorContentHub · Starter content

What is an ArrayList?

A ready-to-use beginner Java short script.

1. Introduction – What is an ArrayList?

[Narration]

Imagine you are developing a student management application. You need to store the names of students. Initially, you have five students, but tomorrow ten more students may join. Next month, the number could become one hundred.

How would you store these names in Java? One option is an array. But arrays have a fixed size. If you create an array with five positions, you cannot directly increase its capacity to accommodate more elements.

This is where ArrayList becomes useful. ArrayList is a class in the Java Collections Framework that provides a resizable array implementation.

In simple words, an ArrayList allows us to store multiple elements and dynamically grow or shrink as elements are added or removed.

We can add, retrieve, update, remove and search for elements using built-in methods.

2. Why do we need ArrayList?

Let's first understand the limitation of a normal array.

String[] names = new String[3];

names[0] = "Asha";
names[1] = "Ravi";
names[2] = "Neha";

Here, we created an array with a capacity of three elements. If we want to add a fourth element, we cannot simply assign it to index 3 because that index does not exist.

We would need to create a new, larger array and copy the existing elements into it.

ArrayList makes this process easier. It manages its internal storage automatically as elements are added.

3. Array vs ArrayList

Let's compare the two:

String[] namesArray = new String[3];

List<String> namesList = new ArrayList<>();

An array has a fixed length after creation. An ArrayList can dynamically grow and shrink.

Arrays can store primitive values directly, such as int and double. ArrayList stores objects, so for primitive values we use wrapper classes such as Integer and Double.

Arrays use the length property to get their size. ArrayList uses the size() method.

int[] numbers = {10, 20, 30};

System.out.println(numbers.length);

List<Integer> numberList = new ArrayList<>();

numberList.add(10);
numberList.add(20);

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

4. How to create an ArrayList

Now let's write our first ArrayList program. First, we need to import the required classes.

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

public class ArrayListExample {

    public static void main(String[] args) {

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

    }
}

Here, List is an interface and ArrayList is its implementation class.

We are using the List reference type because it allows us to write flexible code. We can replace ArrayList with another List implementation when required.

5. Adding elements using add()

To insert elements into an ArrayList, we use the add() method.

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

names.add("Asha");
names.add("Ravi");
names.add("Neha");

System.out.println(names);

Output:

[Asha, Ravi, Neha]

Notice that we did not specify the capacity of the list. We simply added elements. The ArrayList manages its internal capacity as needed.

We can also insert an element at a particular index.

names.add(1, "Priya");

System.out.println(names);

Output:

[Asha, Priya, Ravi, Neha]

The element at index 1 is inserted, and the existing elements from that position shift to the right.

6. Reading elements using get()

To retrieve an element, we use the get() method. Remember that ArrayList uses zero-based indexing.

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

Output:

Asha
Priya
Ravi

Index 0 represents the first element, index 1 represents the second element, and so on.

If we try to access an invalid index, Java throws IndexOutOfBoundsException.

7. Updating elements using set()

Suppose a student's name has changed. We don't need to remove the old element and add a new one. We can directly update it using set().

names.set(1, "Priyanka");

System.out.println(names);

Output:

[Asha, Priyanka, Ravi, Neha]

The set() method replaces the element at the specified index. It does not increase the size of the list.

8. Removing elements using remove()

We can remove an element by its index or by its value.

// Remove element at index 1
names.remove(1);

// Remove an element by its value
names.remove("Neha");

System.out.println(names);

Output:

[Asha, Ravi]

One important point: when we remove an element, the remaining elements shift to fill the gap.

Also remember that remove() has overloaded versions. With an ArrayList of Integer values, remove(1) removes the element at index 1, not necessarily the Integer value 1. To remove the value 1, use Integer.valueOf(1).

9. Finding the number of elements using size()

The size() method returns the current number of elements in the ArrayList.

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

Output:

2

Remember the difference: an array uses length, while an ArrayList uses size().

10. Iterating through an ArrayList

In real applications, we frequently need to process every element in a collection. Java provides several ways to iterate through an ArrayList.

Using a for loop

for (int i = 0; i < names.size(); i++) {
    System.out.println(names.get(i));
}

Using an enhanced for loop

for (String name : names) {
    System.out.println(name);
}

Using forEach()

names.forEach(name -> System.out.println(name));

All three approaches allow us to process the elements. Choose the approach that makes your code easiest to understand.

11. Searching elements using contains()

What if we want to check whether a particular student is present in our list?

We can use the contains() method.

boolean result = names.contains("Asha");

System.out.println(result);

Output:

true

If the element is present, contains() returns true. Otherwise, it returns false.

12. Checking whether an ArrayList is empty

The isEmpty() method tells us whether the list contains any elements.

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

System.out.println(students.isEmpty());

students.add("Asha");

System.out.println(students.isEmpty());

Output:

true
false

13. Practical example – Student management

Now let's combine what we have learned in one practical Java program.

Our requirement is to maintain student names. We will add students, display them, update a name, remove a student and check whether a student exists.

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

public class StudentManagement {

    public static void main(String[] args) {

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

        // Add students
        students.add("Asha");
        students.add("Ravi");
        students.add("Neha");
        students.add("Kiran");

        // Display all students
        System.out.println("Students: " + students);

        // Read one student
        System.out.println("First student: " + students.get(0));

        // Update a student
        students.set(1, "Rahul");

        // Remove a student
        students.remove("Neha");

        // Search for a student
        System.out.println(
            "Is Asha present? " + students.contains("Asha")
        );

        // Display final list
        System.out.println("Final list: " + students);

        // Display total count
        System.out.println("Total students: " + students.size());
    }
}

Expected output:

Students: [Asha, Ravi, Neha, Kiran]
First student: Asha
Is Asha present? true
Final list: [Asha, Rahul, Kiran]
Total students: 3

This small example demonstrates how ArrayList can be used in a real application to manage a changing collection of student records.

14. Important points about ArrayList

  • ArrayList maintains insertion order.
  • It allows duplicate elements.
  • It allows null elements.
  • It supports indexed access.
  • It grows and shrinks dynamically.
  • It is not synchronized by default.
  • It provides fast access by index.
  • Adding or removing elements in the middle may require shifting elements.

15. Common ArrayList interview questions

Q1. What is ArrayList?

ArrayList is a resizable array implementation of the List interface in the Java Collections Framework.

Q2. Does ArrayList allow duplicates?

Yes. ArrayList allows duplicate elements.

Q3. Does ArrayList maintain insertion order?

Yes. It maintains the order in which elements are inserted.

Q4. Is ArrayList synchronized?

No. ArrayList is not synchronized by default.

Q5. Can ArrayList store primitive data types?

ArrayList stores objects. We use wrapper classes such as Integer, Double and Character for primitive values. Java autoboxing and unboxing make conversions convenient.

Q6. What is the difference between length and size()?

Arrays use the length property. ArrayList uses the size() method to return the number of elements currently stored.

Q7. What happens when we access an invalid index?

ArrayList throws IndexOutOfBoundsException.

16. Conclusion and recap

So, today we learned what ArrayList is and why it is useful in Java applications.

We explored how to create an ArrayList and how to add, retrieve, update, remove and search for elements. We also learned how to iterate through a list and implemented a practical student management example.

Remember these important methods:

add()       - Add an element
get()       - Retrieve an element
set()       - Update an element
remove()    - Remove an element
size()      - Get the number of elements
contains()  - Check whether an element exists
isEmpty()   - Check whether the list is empty
clear()     - Remove all elements

If you are learning Java Collections, ArrayList is one of the most important concepts to understand. Practise these methods yourself and try the student management example.

Thanks for watching. Keep learning, keep practising, and I'll see you in the next Java tutorial!

PROMOTE YOUR BUSINESS

Advertise on CreatorContentHub

Reach visitors exploring games, learning content, stories and creator tools.

₹500 per banner / month Advertise with us →