Read Only List in Java

In this example, We will show you how to make read only list in java. The example was tested and output shared in the post.

Example Program

package com.dineshkrish;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* 
* @author Dinesh Krishnan
*
*/
public class ReadOnlyList {
public static void main(String[] args) {
// defining list object
List<String> list = new ArrayList<String>();
// adding the elements
list.add("A");
list.add("B");
list.add("C");
list.add("D");
list.add("E");
// making read only list
list = Collections.unmodifiableList(list);
// trying to update
list.add("F");
System.out.println(list);
}
}

Run it

[su_highlight]Exception in thread “main” java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableCollection.add(Unknown Source)
at com.dineshkrish.ReadOnlyList.main(ReadOnlyList.java:31)[/su_highlight]

References

1. Java List Interface
2. Java ArrayList Class
3. Java Collections Class
4. Java Collections.unmodifiableList() method

No responses yet

Leave a Reply

Your email address will not be published. Required fields are marked *