Saturday 14 July 2018

Arrays.asList() throws UnsupportedOperationException while removing element using iterator

Arrays.asList() creates an immutable list, so you can’t perform any create, update and delete operations on it after creation.

Arrays.asList() do not return the instance of java.util.ArrayList
Arrays class has a private static class ‘ArrayList’. Whenever you call for Arrays.asList() method, it return an instance of type java.util.Arrays$ArrayList, not the instance of java.util.ArrayList.

 Arrays class definition looks like below.
public class Arrays {

 @SafeVarargs
    @SuppressWarnings("varargs")
    public static <T> List<T> asList(T... a) {
        return new ArrayList<>(a);
    }
 
    private static class ArrayList<E> extends AbstractList<E>
        implements RandomAccess, java.io.Serializable
    {
        private static final long serialVersionUID = -2764017481108945198L;
        private final E[] a;

        ArrayList(E[] array) {
            a = Objects.requireNonNull(array);
        }

        @Override
        public int size() {
            return a.length;
        }

        @Override
        public Object[] toArray() {
            return a.clone();
        }

        @Override
        @SuppressWarnings("unchecked")
        public <T> T[] toArray(T[] a) {
            int size = size();
            if (a.length < size)
                return Arrays.copyOf(this.a, size,
                                     (Class<? extends T[]>) a.getClass());
            System.arraycopy(this.a, 0, a, 0, size);
            if (a.length > size)
                a[size] = null;
            return a;
        }

        @Override
        public E get(int index) {
            return a[index];
        }

        @Override
        public E set(int index, E element) {
            E oldValue = a[index];
            a[index] = element;
            return oldValue;
        }

        @Override
        public int indexOf(Object o) {
            E[] a = this.a;
            if (o == null) {
                for (int i = 0; i < a.length; i++)
                    if (a[i] == null)
                        return i;
            } else {
                for (int i = 0; i < a.length; i++)
                    if (o.equals(a[i]))
                        return i;
            }
            return -1;
        }

        @Override
        public boolean contains(Object o) {
            return indexOf(o) != -1;
        }

        @Override
        public Spliterator<E> spliterator() {
            return Spliterators.spliterator(a, Spliterator.ORDERED);
        }

        @Override
        public void forEach(Consumer<? super E> action) {
            Objects.requireNonNull(action);
            for (E e : a) {
                action.accept(e);
            }
        }

        @Override
        public void replaceAll(UnaryOperator<E> operator) {
            Objects.requireNonNull(operator);
            E[] a = this.a;
            for (int i = 0; i < a.length; i++) {
                a[i] = operator.apply(a[i]);
            }
        }

        @Override
        public void sort(Comparator<? super E> c) {
            Arrays.sort(a, c);
        }
    }
 
}

From the definition of ‘java.util.Arrays$ArrayList,’ class, I can confirm that ‘java.util.Arrays$ArrayList, do not support modifications on the list. Whenever you want an immutable list, you can define it using Arrays.asList() method.


Find the below working example.
Test.java
package com.sample.app;

import java.util.Arrays;
import java.util.List;

public class Test {

 public static void main(String args[]) {
  List<Integer> list = Arrays.asList(2, 3, 5);

  try {
   list.add(10);
  } catch (UnsupportedOperationException e) {
   System.out.println("Adding of data to list is not supprted");
  }

  try {
   list.remove(0);
  } catch (UnsupportedOperationException e) {
   System.out.println("Removal of data from list is not supported");
  }

  try {
   list.add(4, 5);
  } catch (UnsupportedOperationException e) {
   System.out.println("Adding od data to list is not supported");
   e.printStackTrace();
  }

 }
}

When you ran Test.java, you can able to see below messages in console.
Adding of data to list is not supprted
Removal of data from list is not supported
Adding od data to list is not supported
java.lang.UnsupportedOperationException
 at java.util.AbstractList.add(AbstractList.java:148)
 at com.sample.app.Test.main(Test.java:24)


You may like

No comments:

Post a Comment