Home »
Java »
Java Articles
How to create a mutable list in Java?
By IncludeHelp Last updated : February 4, 2024
Mutable lists refer to those lists which can be changed i.e., the modifiable lists are known as mutable lists in Java.
Problem statement
The task is to create a mutable list in Java.
Creating mutable list
To create a mutable list in Java, create an ArrayList by passing the immutable list created by the Arrays.asList() method.
Syntax
Below is the syntax to create a mutable list:
List<Integer> list=new ArrayList<>(Arrays.asList(elements));
Java program to create a mutable list
This program creates a mutable list.
// Importing the required classes
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
// Creating main class
public class Main {
public static void main(String args[]) {
// Creating a mutable list
List < Integer > list = new ArrayList < > (
Arrays.asList(10, 20, 30, 40, 50));
// Printing the list
System.out.println("Mutable list is : " + list.toString());
// Modifying the list by adding one more element
list.add(60);
// Printing the list
System.out.println("Modified list is : " + list.toString());
}
}
Output
The output of the above program is:
Mutable list is : [10, 20, 30, 40, 50]
Modified list is : [10, 20, 30, 40, 50, 60]
To understand this program, you should have the basic knowledge of the following Java topics: