The unmodifiableCollection()
method of java.util.Collections
class is used to return 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
.
It is important to notice that objects which are present inside the collection can still be altered.
import java.util.ArrayList; import java.util.Collections; import java.util.List; public class MyUnmodifiableClass { private List<Integer> intList = new ArrayList<>(); public void addValueToIntList(Integer value){ intList.add(value); } public List<Integer> getIntList() { return Collections.unmodifiableList(intList); } }
The following attempt to modify an unmodifiable collection will throw an exception:
import java.util.List; public class Test { public static void main(String[] args) { MyUnmodifiableClass obj = new MyUnmodifiableClass(); obj.addValueToIntList(42); List<Integer> list = obj.getIntList(); list.add(69); } } output: ======= Exception in thread "main" java.lang.UnsupportedOperationException at java.util.Collections$UnmodifiableCollection.add(Collections.java:1055) at Test.main(Test.java:10)
Hope you have enjoyed reading What is Unmodifiable Collection in java?. Please do write us if you have any suggestion/comment or come across any error on this page. Thank you for reading!
Share this page on WhatsApp