Sobes.tech
Junior — Middle

What does modifying an element in an immutable collection mean?

sobes.tech AI

Answer from AI

An immutable collection is a collection whose state cannot be changed after creation. Modifying an element in such a collection means you cannot change the contents of the collection directly (for example, adding, removing, or changing an element).

If you try to modify an element, it will result in a runtime error (such as UnsupportedOperationException) or simply be impossible, as modification methods are not implemented.

To "modify" an element in an immutable collection, you typically create a new collection with the desired changes, leaving the original unchanged. This ensures safety and predictability of the code, especially in multithreaded environments.

Example using List.of (Java 9+):

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

// To "modify" an element, create a new collection:
List<String> newList = new ArrayList<>(list);
newList.set(1, "newB");

Thus, immutability of a collection means that the collection itself does not change, and any modifications require creating a new collection.