Practice mode Java

What happens when the Java code List<Integer> x = List.of(1, 2); x.add(3); is run?

Correct answer C. An UnsupportedOperationException is thrown

Explanation

The factory method List.of returns an unmodifiable list, so any mutator such as add or remove throws UnsupportedOperationException. The code compiles because add is declared on the List interface. To obtain a list that can grow, copy the values into a modifiable implementation, for example new ArrayList(List.of(1, 2)).

Report a problem

Answer checked How we write and check questions

Tip: press A, B, C or D to answer, and N for the next question.

Advertisement

Have a question about this answer?

Your email address will not be published. Required fields are marked *

Links and website addresses are not allowed in comments.