How to create an immutable list in Java?

By IncludeHelp Last updated : February 4, 2024

Problem statement

The task is to create an immutable list in Java.

Creating immutable list

To create an immutable list in Java, you can use the Arrays.asList() method which creates an immutable list from an array.

Syntax

Below is the syntax to create an immutable list from an array:

List<Integer> list = Arrays.asList(elements); 

Java program to create an immutable list

This program creates an immutable list from an array.

// Importing the required classes
import java.util.Arrays;
import java.util.List;

// Creating main cass
public class Main {
  public static void main(String args[]) {
    // Create an immutable list from array
    List < Integer > list = Arrays.asList(10, 20, 30, 40, 50);

    // Printing the list 
    System.out.println("List is : " + list.toString());
  }
}

Output

The output of the above program is:

List is : [10, 20, 30, 40, 50]

To understand this program, you should have the basic knowledge of the following Java topics:

  • Java System.out.println() Method
  • Java Arrays
  • Java Lists

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.