How you create read only collection

How you create read only collection

Answer: Collections class has below methods available to make read only Colleciton, List, Map, Set etc…

How you create read only collection

Below example will show you how to crate read only list and if you try to modify it will throw java.lang.UnsupportedOperationException.

package com.javahonk.blockingqueue;

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

public class ReadOnlyCollection {

	public static void main(String[] args) {

	List<String> list = new ArrayList<String>();
	list.add("Java");
	list.add("Honk");
	list.add("Read only collection");

	Collection<String> collection = 
			Collections.unmodifiableCollection(list);

	Iterator<String> iterator = collection.iterator();
	System.out.println("Origional List");
	while (iterator.hasNext()) {
		String string = (String) iterator.next();
		System.out.println(string);
		if (string.equalsIgnoreCase("Honk")) {
			iterator.remove();
		}
	}

	}

}

 

Output:

How you create read only collection

Leave a Reply

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

I am not Robot *