How to create a read-only List in Java?

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {
	public static void main(String[] argv) throws Exception {
		List<String> myList = new ArrayList<String>();
		myList.add("abc");
		myList.add("def");
		
		myList = Collections.unmodifiableList(myList);

		try {
			myList.add("efg");
			
		} catch (UnsupportedOperationException e) {
			System.out.println("This is a read only collection, you can't modify it");
		}
		
		System.out.println("myList :"+ myList.toString());
	}
}
Output
This is a read only collection, you can't modify it myList :[abc, def]




















Receive Latest Java Examples in Your Email: