Question 9
Back to Exercise
What is the output of the following Java program?
import java.util.ArrayList;
import java.util.List;
record Team(String name, List<String> members) { }
record SafeTeam(String name, List<String> members) {
SafeTeam { members = List.copyOf(members); }
}
public class Main {
public static void main(String[] args) {
List<String> people = new ArrayList<>(List.of("Asha"));
Team t = new Team("A", people);
SafeTeam s = new SafeTeam("B", people);
people.add("Ravi");
t.members().add("Meena");
System.out.println(t.members() + " " + s.members() + " " + people.size());
}
}
- A [Asha, Ravi, Meena] [Asha] 3 Correct
- B [Asha] [Asha] 1
- C [Asha, Ravi, Meena] [Asha, Ravi, Meena] 3
- D [Asha, Meena] [Asha] 2
Correct Answer: Option A
Team shares the caller's list (shallow immutability); SafeTeam copied it in its compact constructor.
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!