Listfruits = new ArrayList<>(); fruits.add("apple"); fruits.add("banana"); fruits.add("orange"); Collection unmodifiableFruits = Collections.unmodifiableCollection(fruits); unmodifiableFruits.add("grape"); // throws UnsupportedOperationException
SetIn this example, we create a HashSet of numbers and pass it to unmodifiableCollection to get an unmodifiable view of the collection. We then print out the unmodifiableNumbers collection and see that it contains the numbers 1, 2, and 3. After that, we add the number 4 to the original numbers collection, but when we print out the unmodifiableNumbers collection again, it still contains only the numbers 1, 2, and 3. The package library for unmodifiableCollection is java.util.Collections.numbers = new HashSet<>(); numbers.add(1); numbers.add(2); numbers.add(3); Collection unmodifiableNumbers = Collections.unmodifiableCollection(numbers); System.out.println(unmodifiableNumbers); // prints [1, 2, 3] numbers.add(4); System.out.println(unmodifiableNumbers); // prints [1, 2, 3]