Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - List asImmutable method



Description

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

Syntax

public List asImmutable()

Parameters

NA

Return Value

A non-modifiable List version of current List.

Example - Getting Immutable List of Integers

Following is an example of the usage of this method −

main.groovy

def mutable = [1,2,3]

// get the unmodifiable list
def immutable = mutable.asImmutable()

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

// print the lists
println(mutable)
println(immutable)

// update the modifiable list
mutable << 4

// print the lists
println(mutable)
println(immutable)

Output

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

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

Example - Getting Immutable List of Strings

Following is an example of the usage of this method −

main.groovy

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

// get the unmodifiable list
def immutable = mutable.asImmutable()

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

// print the lists
println(mutable)
println(immutable)

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

// print the lists
println(mutable)
println(immutable)

Output

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

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

Example - Getting Immutable 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.asImmutable()

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

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 immutable.
groovy_lists.htm
Advertisements