Tuesday, June 7, 2011

Arrays.ArrayList Arrays.asList fixed nature

There are few instances where we assume certain things in the code and finally get into trouble. Today I had to solve a issue by going through a piece of legacy code which gives a good example to that :). I got a UnsupportedOperationException at one point and had no clue why it is coming.

Particular part of the code was similar to this,


String[] inputArray = new String[]{"1", "2", "3"};

List strList = Arrays.asList(inputArray);

strList.add("4");

I get a UnsupportedOperationException when I tried to add a new element "4".

This exception comes because Arrays.asList() methods returns a Arrays.ArrayList class, which differs from the java.util.ArrayList implementation. Arrays.ArrayList is immutable by nature, so that we cannot add/delete any elements from the ArrayList.


String[] inputArray = new String[]{"1", "2", "3"};

List strList = new ArrayList();
strList.addAll(Arrays.asList(inputArray));
strList.add("4");


So we can simply follow this way to avoid the UnsupportedOperationException issue. In future, make sure you will be getting a fixed size ArrayList, when you initiate the ArrayList in the following way.

List strList = Arrays.asList(inputArray);

No comments:

Post a Comment