Wednesday, July 19, 2017

How to make ArrayList Immutable


By default ArrayList is modifiable, JDK gives a very good method to make it immutable.

/*Class to make ArrayList Immutable*/
public class ImmutableArrayList {

     public static void main(String[] args) {
          List<String> list = new ArrayList<>(Arrays.asList("Paras","Sonal","Richa","Usha"));
          List<String> unModificableList=Collections.unmodifiableList(list);
          unModificableList.add("Abc");
     }   
}

Output
Exception in thread "main" java.lang.UnsupportedOperationException
     at java.util.Collections$UnmodifiableCollection.add(Unknown Source)
     at com.ArrayList.ImmutableArrayList.main(ImmutableArrayList.java:14)


No comments:

Post a Comment