Blogger

Delete comment from: Javarevisited

Anonymous said...

There is a limitation of Collections.unmodifiableList(myList) method, it will not work in case of nested lists. For example if your List contains reference to another list then this method will make outer most List unmodifiable, you can still get reference of nested list and can modify it. here is an example, which confirms that :

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


public class Sample {


public static void main(String args[]){

List outer = new ArrayList();
outer.add("C++");
outer.add("C");
outer.add("Python");

List inner = new ArrayList();
inner.add("Java");

outer.add(inner); // adding List to outer List

// read only list
List unmodifiable = Collections.unmodifiableList(outer);

System.out.println("List before modification : " + unmodifiable);

List myInner = (List) unmodifiable.get(3);
myInner.add("JEE");
myInner.add("Java ME");

System.out.println("List after modification : " + unmodifiable);

}


}

When you run this program it will print :
List before modification : [C++, C, Python, [Java]]
List after modification : [C++, C, Python, [Java, JEE, Java ME]]

Which clearly shows that you can still modify inner List, which means unmodifiableList() method is only good if your List doesn't contain another List or Collection.

Dec 16, 2014, 3:58:37 AM


Posted to How to Create Read Only List, Map and Set in Java? UnModifiable Collection Example

Google apps
Main menu