Back to Home

Article

Arrays.asList() – Why You Should Wrap It

August 13, 2013
By Ria Mora
Reading Time : 1
 minute
Array List Image
Back to Home

Article

Arrays.asList() – Why You Should Wrap It

August 13, 2013
By Ria Mora
Reading Time : 1
 minute

Ria shows us why you should wrap a list inside a list implementation if you’re planning to modify it.

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 listOfOtherFiles = Arrays.asList(otherDirectory.listFiles());
List 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 listOfOtherFiles = Arrays.asList(otherDirectory.listFiles());
List fileList = new LinkedList(Arrays.asList(directory.listFiles()));
fileList.removeAll(listOfOtherFiles);
...

Share

Key Topics

O&B Interns

Intern @ O&B

GROW WITH US AND
MAKE A DIFFERENCE

Apply for Internship
O&B Interns

Intern @ O&B

GROW WITH US AND
MAKE A DIFFERENCE

Apply for Internship