Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - List asUnmodifiable method



Description

Groovy List asUnmodifiable() method is a convenience method to get an unmodifiable version of the current list. Changes are not supported in this list.

Syntax

public List asUnmodifiable()

Parameters

NA

Return Value

A non-modifiable List version of current List.

Example - Getting unmodifiable List of Integers

Following is an example of the usage of this method −

main.groovy

def modifiable = [1,2,3]

// get the unmodifiable list
def unmodifiable = modifiable.asUnmodifiable()

try {
   // try to append element to unmodifiable list
   unmodifiable << 4
}catch(UnsupportedOperationException e) {
    println("List is unmodifiable.")
}

// print the lists
println(modifiable)
println(unmodifiable)

// update the modifiable list
modifiable << 4

// print the lists
println(modifiable)
println(unmodifiable)

Output

When we run the above program, we will get the following result −

List is unmodifiable.
[1, 2, 3]
[1, 2, 3]
[1, 2, 3, 4]
[1, 2, 3, 4]

Example - Getting unmodifiable List of Strings

Following is an example of the usage of this method −

main.groovy

def modifiable = ["Apple","Mango","Orange"]

// get the unmodifiable list
def unmodifiable = modifiable.asUnmodifiable()

try {
   // try to append element to unmodifiable list
   unmodifiable << "Papaya"
}catch(UnsupportedOperationException e) {
    println("List is unmodifiable.")
}

// print the lists
println(modifiable)
println(unmodifiable)

// update the modifiable list
modifiable << "Papaya"

// print the lists
println(modifiable)
println(unmodifiable)

Output

When we run the above program, we will get the following result −

List is unmodifiable.
[Apple, Mango, Orange]
[Apple, Mango, Orange]
[Apple, Mango, Orange, Papaya]
[Apple, Mango, Orange, Papaya]

Example - Getting unmodifiable List of Objects

Following is an example of the usage of this method −

main.groovy

def lst = [];
		
lst.add(new Student(1, "Julie"));
lst.add(new Student(2, "Robert"));
println(lst)

def readOnlyList = lst.asUnmodifiable()

try {
   // try to append element to unmodifiable list
   readOnlyList << new Student(3, "Adam")
}catch(UnsupportedOperationException e) {
    println("List is unmodifiable.")
}

class Student {
   int rollNo;
   String name;

   Student(int rollNo, String name){
      this.rollNo = rollNo;
      this.name = name;
   }

   @Override
   public String toString() {
      return "[ " + this.rollNo + ", " + this.name + " ]";
   }
}

Output

When we run the above program, we will get the following result −

[[ 1, Julie ], [ 2, Robert ]]
List is unmodifiable.
groovy_lists.htm
Advertisements