1

By executing below code why i get the java.lang.UnsupportedOperationException

Here is Code.

public static void main(String[] args) {
        List<String> strs = Arrays.asList("One","Two","Three","Four");

        Consumer<String> upperCaseConsumer = s -> strs.add(s.toUpperCase());
        Consumer<String> printConsumer = s -> System.out.println(s);

        strs.forEach(upperCaseConsumer);
        strs.forEach(printConsumer);
}
RBS
  • 207
  • 1
  • 11

1 Answers1

1

Arrays.asList("One","Two","Three","Four") returns a constant size List backed by an array, so you can't add elements to it.

Use

List<String> strs = new ArrayList<>(Arrays.asList("One","Two","Three","Four")); 

instead.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • By Executing List strs = Arrays.asList("One","Two","Three","Four"); System.out.println(strs.getClass().getSimpleName()); it gives me class name ArrayList And By executing List strs = new ArrayList<>(Arrays.asList("One","Two","Three","Four")); System.out.println(strs.getClass().getSimpleName()); it also give me ArrayList so how it makes difference whether i create arraylist by asList or using new ? – RBS Mar 03 '20 at 07:12
  • @RBS It's not the same ArrayList. The former is `java.util.Arrays$ArrayList` and the latter is `java.util.ArrayList` – Eran Mar 03 '20 at 07:15
  • Thanks, i need to read more in details for it. – RBS Mar 03 '20 at 07:18