Sobes.tech
Junior — Middle

What are the consequences of attempting to modify an immutable collection?

sobes.tech AI

Answer from AI

If you try to modify a collection declared as immutable (for example, List.of() in Java 9+ or Collections.unmodifiableList()), an UnsupportedOperationException will be thrown.

This happens because immutable collections do not support modification operations such as add(), remove(), or clear(). Attempting to modify such a collection violates its contract and results in a runtime error.

Example:

List<String> immutableList = List.of("a", "b", "c");
immutableList.add("d"); // will throw UnsupportedOperationException

Thus, immutable collections provide safety against accidental modifications and can be used for data transfer without the risk of modification.