java-How to iterate and remove element from Arrays.asList result.

1. The purpose of this post

This post would demo how to solve this exception when we iterate and remove an element from an arraylist :

Exception in thread "main" java.lang.UnsupportedOperationException
    at java.util.AbstractList.remove(AbstractList.java:161)
    at java.util.AbstractList$Itr.remove(AbstractList.java:374)
    at java8.learn.collections.IterRemove.main(IterRemove.java:16)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)

2. Environments

  • java 1.8+

3. How to reproduce this exception

List<String> all = Arrays.asList("a","b","c");
for(Iterator<String> iter = all.iterator();iter.hasNext();) {
    if(iter.next().equals("b")) {
        iter.remove();
    }
}
all.forEach(i-> System.out.println(i));

If we run it, we got the above error.

4. How to solve this exception

Change your code like this:

List<String> all = new ArrayList<>(Arrays.asList("a","b","c"));
for(Iterator<String> iter = all.iterator();iter.hasNext();) {
    if(iter.next().equals("b")) {
        iter.remove();
    }
}
all.forEach(i-> System.out.println(i));

rerun the code, then we get this:

a
c

Process finished with exit code 0

5. Why

The asList() method of java.util.Arrays class is used to return a fixed-size list backed by the specified array. This method acts as bridge between array-based and collection-based APIs, in combination with Collection.toArray().

So, if you want to change the result of the Arrays.asList, you must wrap it with a new ArrayList.