CodesJava

Easy learning with example program codes

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.codesjava;
 
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.codesjava.Test.main(Test.java:27)

Java Collections class examples

Sign Up/ Sign In
Ask a Question


Industrial Training

We offers Placement Oriented Training on Java, Spring, JSF, Hibernate, PHP, AngularJS, Angular 4, PLSQL, Oracle BI Publisher etc. We also provides Online training, please mail us at hr@codesjava.com.

Development

We also provides the Development services for Website Development , Java Development, PHP Development, Android App Development etc. You can contact us on hr@codesjava.com.

Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki