Question 7
Back to Exercise
What is the output of the following Java program?
import java.util.ArrayList;
import java.util.List;
class Log {
private final List<String> lines = new ArrayList<>();
void write(String s) { lines.add(s); }
List<String> snapshot() { return List.copyOf(lines); }
}
public class Main {
public static void main(String[] args) {
Log log = new Log();
log.write("start");
List<String> snap = log.snapshot();
log.write("step 1");
log.write("end");
System.out.println(snap + " " + log.snapshot().size());
}
}
- A [start] 3 Correct
- B [start, step 1, end] 3
- C [start] 1
- D [] 3
Correct Answer: Option A
copyOf freezes the contents at that moment, unlike an unmodifiable view.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!