Java ArrayList CRUD Operations Example

1. Introduction

In Java, ArrayList is a part of the collection framework and resides in the java.util package. It provides dynamic arrays in Java. ArrayList supports dynamic arrays that can grow as needed. In this post, we'll be looking at the CRUD (Create, Read, Update, Delete) operations that can be performed on an ArrayList.

Learn everything about ArrayList: ArrayList Java Tutorial

2. Program Steps

1. Initialize an ArrayList.

2. Add elements to the ArrayList (Create).

3. Retrieve elements from the ArrayList (Read).

4. Modify elements in the ArrayList (Update).

5. Remove elements from the ArrayList (Delete).

6. Display the final ArrayList.

3. Code Program

import java.util.ArrayList;

public class ArrayListCRUDExample {
    public static void main(String[] args) {
        // 1. Initialize an ArrayList
        ArrayList<String> fruits = new ArrayList<>();

        // 2. Add elements to the ArrayList (Create)
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");
        System.out.println("After adding elements: " + fruits);

        // 3. Retrieve elements from the ArrayList (Read)
        String firstFruit = fruits.get(0);
        System.out.println("First fruit: " + firstFruit);

        // 4. Modify elements in the ArrayList (Update)
        fruits.set(1, "Blueberry");
        System.out.println("After updating second element: " + fruits);

        // 5. Remove elements from the ArrayList (Delete)
        fruits.remove("Cherry");
        System.out.println("After removing Cherry: " + fruits);

        // 6. Display the final ArrayList
        System.out.println("Final ArrayList: " + fruits);
    }
}

Output:

After adding elements: [Apple, Banana, Cherry]
First fruit: Apple
After updating second element: [Apple, Blueberry, Cherry]
After removing Cherry: [Apple, Blueberry]

4. Step By Step Explanation

1. We first initialize an empty ArrayList named fruits.

2. We then add three fruits to the list using the add method.

3. To retrieve an element, we use the get method, providing its index.

4. We utilize the set method to update an element by specifying the index and the new value.

5. The remove method deletes an element from the list. We can either provide the index or the object itself.

6. Throughout the operations, we print the status of the ArrayList to observe the changes made.

The above program showcases the basic CRUD operations that can be performed on an ArrayList. It provides a foundational understanding of managing data using dynamic arrays in Java.

Learn everything about ArrayList: ArrayList Java Tutorial

Comments