Main Tutorials

What is java.util.Arrays$ArrayList?

The java.util.Arrays$ArrayList is a nested class inside the Arrays class. It is a fixed size or immutable list backed by an array.

Arrays.java

    public static <T> List<T> asList(T... a) {
        return new ArrayList<>(a);
    }

    /**
     * @serial include
     */
    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);
        }

        //...

    }

The method Arrays.asList returns this class java.util.Arrays$ArrayList.


  List<String> list = Arrays.asList("1", "2", "3", "4", "5");

  System.out.println(list.getClass()); // class java.util.Arrays$ArrayList

UnsupportedOperationException

If we modify an immutable list, it throws UnsupportedOperationException.


  // immutable list
  List<String> list = Arrays.asList("1", "2", "3", "4", "5");
  list.remove("3");

Output


Exception in thread "main" java.lang.UnsupportedOperationException: remove
	at java.base/java.util.Iterator.remove(Iterator.java:102)
	at java.base/java.util.AbstractCollection.remove(AbstractCollection.java:299)

On the other hand, the standalone java.util.ArrayList class returns a mutable list; it allow us to modify the List.


  List<String> list = new ArrayList<>();
  list.add("1");
  list.add("2");
  list.add("3");
  list.add("4");
  list.add("5");

  list.remove("3"); // no exception

References

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
hzhong
1 year ago

Is it better to use unmodifiable instead of immutable? According to Java Collections Framework, unmodifiable and immutable are two different terms.