Immutable Lists (List.of and List.copyOf)
Problem
Read an array. Make a read-only list of its different values in ascending order. Print list: followed by the values. Then try to add the number 0 to the read-only list and print modify: failed (or modify: succeeded if it was possible).
Constraints
- 1 <= n <= 1000
Examples
Input
5 3 1 2 3 1
Output
list: 1 2 3 modify: failed
Solutions
An unmodifiable wrapper protects the list from callers, but the original ArrayList can still change underneath it.
/*
* Problem : Process an array.
* Input : n, then n integers.
* Output : The list and a modify test.
* Approach: Read-only collections.
* Time : O(n log n)
* Space : O(n)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static String[] solve(int[] a) {
// Step 1: Make a sorted set of the different numbers. TreeSet keeps them sorted.
java.util.TreeSet<Integer> set = new java.util.TreeSet<>();
for (int value : a) {
set.add(value);
}
// Step 2: Before Java 9 we need two steps: make a list, then wrap it as unmodifiable.
java.util.List<Integer> list = java.util.Collections.unmodifiableList(new java.util.ArrayList<>(set));
// Step 3: Try to change the list. An unmodifiable list throws UnsupportedOperationException.
String modify;
try {
list.add(0);
modify = "succeeded";
} catch (UnsupportedOperationException error) {
modify = "failed";
}
// Step 4: Print the result.
StringBuilder text = new StringBuilder();
for (int value : list) {
text.append(text.length() == 0 ? "" : " ").append(value);
}
return new String[] {"list: " + text, "modify: " + modify};
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = scanner.nextInt();
}
System.out.println(String.join("\n", solve(a)));
}
}
Hints (1)
- Which exception shows that a list is read-only?