Implement an immutable collection holder
To implement an immutable collection holder, you need to ensure that the list of strings it holds cannot be modified after it is assigned. This can be done by creating an unmodifiable copy of the list in the constructor and returning an unmodifiable view of the list in the getter method. Using Collections.unmodifiableList is a common way to achieve this in Java. import java.util.List; import java.util.ArrayList; import java.util.Collections; public class Main { public static void main(String[] args) { List<String> list = Arrays.asList("apple", "banana", "cherry"); ImmutableCollectionHolder holder = Answer.createImmutableCollectionHolder(list); System.out.println("Immutable list: " + holder.getItems()); // Try to modify the list through the getter try { holder.getItems().add("date"...
Comments
Post a Comment