To further explain a bit the reason behind why adding (and deleting) from an ArrayList
created through Arrays.asList (array)
is not permitted and throws UnsupportedOperationException
, first we know that what this Arrays.asList(...)
does is to convert an array to its equivalent instance of ArrayList
:
String[] strArr = new String[]{"a","b","c"};
List<String> strList = Arrays.asList(strArr);
What's happening here is your strArr
is actually a backing array for strList
, meaning if you modify strArr[0]
then the value at strList.get(0)
will also follow suit, and vice versa. Yes, their values will sync and will remain consistent to each other. This is why you cannot do an addition or deletion for strList
because the backing array will cry and panic as it cannot fulfill it as it is fixed-length (arrays are always fixed size as we know, if you need to resize an array, you need to create a whole new array altogether, resize an existing one is not possible); thus it throws UnsupportedOperationException
.
So the solution, as already mentioned by @ByeBye, is to wrap it with an ArrayList
so it would be a new independent ArrayList
with no backing array whatsoever and has freedom to do addition and deletion.