Collections public static List unmodifiableList(List list) Method Example Program


Returns an unmodifiable view of the specified list. This method allows modules to provide users with "read-only" access to internal lists. Query operations on the returned list "read through" to the specified list, and attempts to modify the returned list, whether direct or via its iterator, result in an UnsupportedOperationException.

Program

package com.candidjava;

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

/**
 * 
 * @author karthikeyan.T
 * @description the following code shows how to use
 *              Collections.unmodifiableList(Map <? extends K,? extends V> m)
 *              method
 */
public class CollectionsUnmodifiableList {
	public static void main(String args[]) throws Exception {
		List<String> list = new ArrayList<String>();
		list.add("karthik");
		list.add("mohan");
		list.add("hari");
		list.add("kamal");
		list = Collections.unmodifiableList(list);
		list.add(1, "Mohan");
		System.out.println(list);
	}
}

Output

Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableList.add(Unknown Source)
at com.candidjava.CollectionsUnmodifiableList.main(CollectionsUnmodifiableList.java:22)

Explanation

public static <T> List<T> unmodifiableList(List<? extends T> list)
Returns an unmodifiable view of the specified list. This method allows modules to provide users with "read-only" access to internal lists. Query operations on the returned list "read through" to the specified list, and attempts to modify the returned list, whether direct or via its iterator, result in an UnsupportedOperationException.
The returned list will be serializable if the specified list is serializable. Similarly, the returned list will implement RandomAccess if the specified list does.

Parameters:
list - the list for which an unmodifiable view is to be returned.
Returns:
an unmodifiable view of the specified list.


Related Post

Comments


©candidjava.com