So QOD is How to make a list as unmodifiable in Java. ? Infact Collections class has method to ensure to create unmodifiable list. Note that unmodifiable ! = immutable.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
// How to make the arraylist unmodifiable.
public class Ques1 {
public static void main(String args[]){
List
arrList.add(new String("SK"));
arrList.add(new String("PK"));
List
try{
unmodifiableList.add("NK");
}catch(Exception e){
e.printStackTrace();
}
// Making it unmodified again.
List
newList.add("NK");
System.out.println("Added NK");
for( String element : arrList){
System.out.println(element);
}
for( String element : newList){
System.out.println(element);
}
}
}
Now how to check if the unmodifiable list is not immutable?
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
// How to make the arraylist unmodifiable.
public class Ques1 {
public static void main(String args[]){
List
arrList.add(new StringBuffer("SK"));
arrList.add(new StringBuffer("PK"));
List
try{
StringBuffer str = unmodifiableList.get(0);
str.append("New");
unmodifiableList.add(new StringBuffer("NK"));
}catch(Exception e){
e.printStackTrace();
}
// Making it unmodified again.
List
newList.add(new StringBuffer("NK"));
System.out.println("Added NK");
for( StringBuffer element : arrList){
System.out.println(element);
}
for( StringBuffer element : newList){
System.out.println(element);
}
}