Thursday, July 30, 2009

Create Read Only List

You can create read only List using Collections, complete code is given bellow:

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

/*
* @author: Prabir Karmakar
*/

public class UnModifiable
{
   private List list = null;
   private List fixed = null;

   public void initializeList(String args[])
       throws Exception
   {
      if(args.length<=0)          throw new Exception("Empty String: please enter string");       list = new ArrayList();
      for(String elem : args)
      {
         list.add(elem);
      }
   }

   public void
createUnmodifiableList()
   {
     fixed = new ArrayList();
     fixed = Collections.unmodifiableList(list);
   }

   public void doSomeChange(String str)
   {
     if(fixed==null)
       throw new NullPointerException("Read-Only list not initialized.");
     try
     {
       fixed.add(str);
     }catch(UnsupportedOperationException uox)
     {
        throw new UnsupportedOperationException("Can't modify readonly list.");
     }
   }

   public void fetch()
   {
     for(String str : list)
     {
       System.out.println(str);
     }
   }

   public static void main(String arg[])
   {
     UnModifiable unList = new UnModifiable();
     String param[] = {"prabir","rahul","kumar"};
     try
     {
       unList.initializeList(param);
       unList.createUnmodifiableList();
       unList.fetch();
       unList.doSomeChange("raj");
      }catch(Exception ex)
      {
        System.out.println(ex.getMessage());
      }
   }
}

No comments:

Post a Comment