Home » Java programming language

Java Collections unmodifiableList() Method with Example

Collections Class unmodifiableList() method: Here, we are going to learn about the unmodifiableList() method of Collections Class with its syntax and example.
Submitted by Preeti Jain, on February 08, 2020

Collections Class unmodifiableList() method

  • unmodifiableList() method is available in java.util package.
  • unmodifiableList() method is used to get a non-modifiable view of the given List (l).
  • unmodifiableList() method is a static method, it is accessible with the class name and if we try to access the method with the class object then also we will not get any error.
  • unmodifiableList() method does not throw an exception at the time of returning an unmodifiable view of the given list.

Syntax:

    public static List unmodifiableList(List l) ;

Parameter(s):

  • List l – represents the list object for which a non-modifiable view is to be retrieved.

Return value:

The return type of this method is List, it returns an unmodifiable view of the given list.

Example:

// Java program to demonstrate the example 
// of List unmodifiableList()
// method of Collections

import java.util.*;

public class UnmodifiableListOfCollections {
    public static void main(String args[]) {
        // Instantiates a linked list object
        List ll = new LinkedList();

        // By using add() method is to add
        // objects in a linked list 
        ll.add(10);
        ll.add(20);
        ll.add(30);
        ll.add(40);
        ll.add(50);

        // Display Linked list
        System.out.println("LinkedList: " + ll);

        // By using unmodifiableList() method is to
        // represent the linked lis in an unmodifiable view
        ll = Collections.unmodifiableList(ll);

        // We will get an exception when we
        // try to add an object in an unmodifiable
        // linked list

        /* ll.add(60);*/
    }
}

Output

LinkedList: [10, 20, 30, 40, 50]


Comments and Discussions!

Load comments ↻





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