Thursday, August 31, 2017

Arrays.asList() in java

Modifying a List returned by Arrays.asList(array)

asList() convert a fixed array into a fixed size list on which no modification can take place. If try to modify, it gives UnsupportedOperationException 

public class ListModified {
   public static void main(String[] args) {
      Integer[] values = { 1, 3, 7 };
      /*
       * Returns a fixed-size list backed by
         the specified array.
       */
      List<Integer> list = Arrays.asList(values);
      System.out.println("List size is " + list.size()
      + " List is " + list);

      /*
       * When trying to modify the list, It gives
       * UnsupportedOperationException
       */
      list.add(10);
      System.out.println(list);
   }
}

Summary

When we use Arrays.asList the size of the returned list is fixed because the list returned is not java.util.ArrayList, but a private static class defined inside java.util.Arrays. So if we add or remove elements from the returned list, an UnsupportedOperationException will be thrown.

Even if I try to remove an element from the list , it would give us UnsupportedOperationException 

No comments:

Post a Comment