how to create immutable list in java?

The java.util.Collections class consists exclusively of static methods that operate on or return collections. It contains polymorphic algorithms that operate on collections, “wrappers”, which return a new collection backed by a specified collection, and a few other odds and ends.

Collections.unmodifiableList() method is used to create immutable list in java. It will throws an exception if we try to add, remove or shift elements.

Example

package com.w3spoint;
 
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
 
public class Test {
  public static void main(String args[]){
	//create list
	List<String> list = new ArrayList<String>();
	//Add elements
	list.add("Jai");
	list.add("Vivek");
	list.add("Mahesh");
	list.add("Vishal");
	list.add("Hemant");
	//Print list elements
        Iterator<String> iterator = list.iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }
 
        //Make this list as immutable
        List<String> immutableList = Collections.unmodifiableList(list);
        //Add elements
        immutableList.add("Naren");  
        System.out.println("Immutable list elements:");
        iterator = immutableList.iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }        
  }
}

Output

Jai
Vivek
Mahesh
Vishal
Hemant
Exception in thread "main" java.lang.UnsupportedOperationException
	at java.util.Collections$UnmodifiableCollection.add(Unknown Source)
	at com.w3spoint.Test.main(Test.java:27)

Java Collections class examples

Please follow and like us:
Content Protection by DMCA.com