Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List throwing UnsupportedOperationException

Tags:

java

I have the sample code below:

String[] patternArray = {"1","2","3"};
List<String> patternCheck = Arrays.asList(patternArray);
patternCheck.add("4");

and the following exception was thrown

Exception in thread "main" java.lang.UnsupportedOperationException
    at java.util.AbstractList.add(Unknown Source)
    at java.util.AbstractList.add(Unknown Source)

My question is why I am not able to add new string to my list?

like image 720
commit Avatar asked Jun 12 '13 08:06

commit


2 Answers

Because Arrays.asList(patternArray); returns a fixed-size list, e.g. you cannot add more elements.

like image 73
Konstantin Yovkov Avatar answered Dec 04 '22 15:12

Konstantin Yovkov


Arrays.asList(..) return an unmodifiable collection. If you want to modify it, make a copy:

List<String> list = new ArrayList<>(Arrays.asList(..))

Alternatively, you can use guava:

List<String> list = Lists.newArrayList("1", "2", "3");
like image 28
Bozho Avatar answered Dec 04 '22 16:12

Bozho