Skip to content
 

Arrays.asList essentially returns an immutable List

Well… it may not be the most earth-shattering realisation and you can probably get the take home message just from the title of the post, but who knew that you get a runtime exception when you try to modify (e.g. add or remove) anything from a List that has been returned from the Arrays.asList method in Java?

        private static List dictionary = Arrays.asList(sampleDescription.split(" "));

	private static String[] dictionaryArray;

	static {
		// throw a few random buzzwords into the mix which may or may not appear in job descriptions
		dictionary.add("Java");
		dictionary.add("SCRUM");
		dictionary.add("Agile");
		dictionary.add("London");
        ...

Unfortunately this code will throw an UnsupportedOperationException when dictionary.add gets called. The guys at Google are quick to the rescue and if you have their Guava or Collections libraries in your project you can resolve this issue by replacing the line with Array.asList with the following code:

private static List dictionary = Lists.newArrayList(sampleDescription.split(" "));

However, it is worth considering that too much copying and converting of Lists and Arrays could expose an element of bad design in the code. It is always worth considering what you’re trying to achieve and if there is a more efficient way to do so.

Leave a Reply