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?
Because Arrays.asList(patternArray);
returns a fixed-size list, e.g. you cannot add more elements.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With