How to create a mutable list in Java

In this tutorial, we will see how to create a mutable list in Java programming language.

A mutable list is an important  element of the Java programming language. It provides a way to create, access and modify lists of data within a program. In this article, we expalin what exactly a Java mutable is and the various ways they can be used .

A mutable list in Java is a type of  data structure that stores items in an array-like structure. Unlike other programming languages, mutable lists in Java are flexible, allowing data to be added, removed, or changed after the list is created.

In Java, a mutable list can hold any type of data, including primitives (e.g. int an double) and objects.

Code to create a mutable list in Java:

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

public class MutableList {
    public static void main(String[] args) {
        // Creating an ArrayList of Strings 
        List<String> mutableList = new ArrayList<>();

        // Adding elements to the ArrayList
        mutableList.add("Jackfruit");
        mutableList.add("Pomegranate");
        mutableList.add("Watermelon");

        System.out.println("Original ArrayList: " + mutableList);

        // Modifying the ArrayList
        mutableList.add("Strawberry");
        mutableList.remove("Jackfruit");

        System.out.println("Modified ArrayList: " + mutableList);

        // Accessing elements by index
        String secondElement = mutableList.get(1);
        System.out.println("Second element: " + secondElement);

        // Updating an element
        mutableList.set(0, "Papaya");
        System.out.println("Updated ArrayList: " + mutableList);
    }
}

Output:

Original ArrayList: [Jackfruit, Pomegranate, Watermelon]
Modified ArrayList: [Pomegranate, Watermelon, Strawberry]
Second element: Watermelon
Updated ArrayList: [Papayya, Watermelon, Strawberry]

Explanation:

The code creates a mutableArrayList of strings, adds and removes element from it, and demonstrates accessing and updating elements in the list. It prints the list at different stages to show the changes made. The operations performed include adding, reomoving, accessing by index, and updating elements in the list.

 

Leave a Reply

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