Back to questions
JuniorTheoryCommon
What happens when this program is compiled and run?
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> xs = List.of("a");
xs.add("b");
System.out.println(xs);
}
}An UnsupportedOperationException is thrown
- Expecting
[a, b]:List.ofcreates an immutable list, andadd,removeandseton it throw; copy it intonew ArrayList<>(...)to change it. - Expecting a compile error: the type
Listdeclaresadd, so the call compiles; the list refuses the change only at run time.
- How do you get a list you can change from
List.of("a")? - What happens if you call
set(0, "b")on the same list?