Runtime Problem with Arrays.asList()

Few days back I came across this interesting problem. One of my friend called me up and asked that following code is compiling without any error but showing “java.lang.UnsupportedOperationException”  in runtime.

public class Test {
    public static void main(String[] args) {
        String[] words = {“ace”, “boom”, “crew”, “dog”, “eon”};
          List<String> wordList = Arrays.asList(words);
          //Create list of words to be removed.
          List<String> toBeRemoved = new ArrayList<String>();
          toBeRemoved.add(“ace”);
          //Remove all the strings present in toBeRemoved
          wordList.removeAll(toBeRemoved);
          for (String e : wordList) {
             System.out.println(e);
          }
    }
}

Error:-

C:\Users\xyz>java Test
Exception in thread “main” java.lang.UnsupportedOperationException
        at java.util.AbstractList.remove(AbstractList.java:144)
        at java.util.AbstractList$Itr.remove(AbstractList.java:360)
        at java.util.AbstractCollection.removeAll(AbstractCollection.java:337)
        at Test.main(Test.java:13)

 

He wanted me to find the reason for this runtime behavior and solve it. After analyzing the code I found that Arrays.asList() does not return instance of java.util.ArrayList. It returns instance of static class java.util.Arrays.ArrayList. When we call removeAll() it in turn calls AbstractList.remove() and this method throws hrow new UnsupportedOperationException.

One solution could to change the code to use java.util.ArrayList instead of java.util.Arrays.ArrayList .

Modified working code:

public class Test {
    public static void main(String[] args) {
        String[] words = {“ace”, “boom”, “crew”, “dog”, “eon”};
          List<String> wordList = new ArrayList<String>(Arrays.asList(words));
          //Create list of words to be removed.
          List<String> toBeRemoved = new ArrayList<String>();
          toBeRemoved.add(“ace”);
          //Remove all the strings present in toBeRemoved
          wordList.removeAll(toBeRemoved);
          for (String e : wordList){
             System.out.println(e);
          }
    }
}

 
Output:- C:\Users\123916>java Test

boom
crew
dog
eon

Advertisements

One response to “Runtime Problem with Arrays.asList()

  1. Nice article. This site is very useful for me.

    Keep posting java memory management, serialization….

    Great job…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s