Collections public static Collection unmodifiableCollection(Collection c) Method Example Program


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

Program

package com.candidjava;

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

/**
 * 
 * @author karthikeyan.T
 * @description the following code shows how to use
 *              Collections.unmodifiableCollection(Collection <? extends T> c)
 *              method.
 */
public class CollectionsUnmodifiableCollections {
	public static void main(String[] args) {
		List<Character> list = new ArrayList<Character>();
		list.add('X');
		list.add('Y');
		System.out.println("Initial list: " + list);
		Collection<Character> immutablelist = Collections
				.unmodifiableCollection(list);
		immutablelist.add('Z');
	}
}

Output

 Initial list: [X, Y]
Exception in thread "main" 
java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableCollection.add(Unknown Source)
at com.candidjava.CollectionsUnmodifiableCollections.main(CollectionsUnmodifiableCollections.java:23)

Explanation

public static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c)
Returns an unmodifiable view of the specified collection. This method allows modules to provide users with "read-only" access to internal collections. Query operations on the returned collection "read through" to the specified collection, and attempts to modify the returned collection, whether direct or via its iterator, result in an UnsupportedOperationException.
The returned collection does not pass the hashCode and equals operations through to the backing collection, but relies on Object's equals and hashCode methods. This is necessary to preserve the contracts of these operations in the case that the backing collection is a set or a list.

The returned collection will be serializable if the specified collection is serializable.

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


Related Post

Comments


©candidjava.com