In this Q&A, we'll go over how to get access to unmodifiable collection.
You can use Collections.unmodifiable<Set|Map|List> methods to get access to an unmodifiable collection.
Any write operations on the unmodifiable collection object will throw UnsupportedOperationException.
Please note the following
Any write operations on the unmodifiable collection object will throw UnsupportedOperationException.
Please note the following
- unmodifiable collection only maintains the structural integrity of the collection. Mutable objects in collection can still be mutated. Please see code below
- collection can still be modified using a modifiable reference
- unmodifiable class is a static nested class within Collections class. It is not exposed via the collections framework
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Unmodifiable {
static class inner {
private int i;
inner(int i) {
this.i = i;
}
public int getI() {
return i;
}
public void setI( int _i) {
i = _i;
}
}
public static void main(String[] args ) {
List<inner> l = new ArrayList<>(1000);
System.out.println( "In setup");
for(int i=0; i < 1000; ++i) {
l.add(new inner(i));
}
// Note that return value is List not UnmodifiableList
List<inner> ul = Collections.unmodifiableList(l);
// element values can be changed
ul.get(0).setI(2);
assert(ul.get(0).getI() == 2);
try {
ul.add(new inner(1001));
}
catch( Exception e) {
// Cannot add/remove elements to unmodifiable list
System.out.println(e.toString());
assertEquals("caught exception", true, true);
}
}
}
import java.util.Collections;
import java.util.List;
public class Unmodifiable {
static class inner {
private int i;
inner(int i) {
this.i = i;
}
public int getI() {
return i;
}
public void setI( int _i) {
i = _i;
}
}
public static void main(String[] args ) {
List<inner> l = new ArrayList<>(1000);
System.out.println( "In setup");
for(int i=0; i < 1000; ++i) {
l.add(new inner(i));
}
// Note that return value is List not UnmodifiableList
List<inner> ul = Collections.unmodifiableList(l);
// element values can be changed
ul.get(0).setI(2);
assert(ul.get(0).getI() == 2);
try {
ul.add(new inner(1001));
}
catch( Exception e) {
// Cannot add/remove elements to unmodifiable list
System.out.println(e.toString());
assertEquals("caught exception", true, true);
}
}
Comments
Post a Comment