Thursday, April 22, 2010

Question of Day (QOD series)

I thought of this idea to start QOD series.. This will ask a question for the day..

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 = new ArrayList();
arrList.add(new String("SK"));
arrList.add(new String("PK"));
List unmodifiableList = Collections.unmodifiableList(arrList);

try{
unmodifiableList.add("NK");
}catch(Exception e){
e.printStackTrace();
}

// Making it unmodified again.
List newList = new ArrayList(unmodifiableList);
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 = new ArrayList();
arrList.add(new StringBuffer("SK"));
arrList.add(new StringBuffer("PK"));
List unmodifiableList = Collections.unmodifiableList(arrList);

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 = new ArrayList(unmodifiableList);
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);
}
}

No comments: