Arrays.asList() – Why You Should Wrap It

oh noes!
I was trying to get the difference of two lists of files when a wild UnsupportedOperationException appeared!

My code looked a lil’ something like this:

...
List<File> listOfOtherFiles = Arrays.asList(otherDirectory.listFiles());
List<File> fileList = Arrays.asList(directory.listFiles());
fileList.removeAll(listOfOtherFiles);
...

The culprit: Arrays.asList().

According to the docs, Arrays.asList() returns a fixed size list. This means that you can’t remove an element from said list nor add to it.

This is why if you’re planning to modify the list, you should wrap it inside a List implementation.

...
List<File> listOfOtherFiles = Arrays.asList(otherDirectory.listFiles());
List<File> fileList = new LinkedList(Arrays.asList(directory.listFiles()));
fileList.removeAll(listOfOtherFiles);
...

Leave a Reply

Your email address will not be published. Required fields are marked *