Make an object that can never change: final fields, copies in and out, and "with" methods that return new objects.
Java · intermediate · 8 min · 24 steps · free
import java.util.ArrayList;
import java.util.List;
final class Team { // final: no subclass can change behaviour
private final String name;
private final List<String> members;
Team(String name, List<String> members) {
this.name = name;
this.members = new ArrayList<>(members); // defensive copy in
}
List<String> members() {
return List.copyOf(members); // read-only copy out
}
Team withMember(String m) { // "changes" make a new object
List<String> more = new ArrayList<>(members);
more.add(m);
return new Team(name, more);
}
}
public class ImmutableDemo {
public static void main(String[] args) {
List<String> start = new ArrayList<>(List.of("ana"));
Team t1 = new Team("blue", start);
start.add("hacker"); // does not affect t1
Team t2 = t1.withMember("ben");
System.out.println(t1.members() + " " + t2.members());
}
}main. args holds its command-line arguments (none here). start is created on the stack and points to a new ArrayList on the heap: ["ana"].Object) runs first.name in the Team object changes from null to "blue".Team() has finished, so its variables are gone.withMember(), with m = "ben". It gets its own variables on the stack.more points to.Team constructor to set up the new object, with name = "blue" and members = ["ana", "ben"].Object) runs first.name in the Team object changes from null to "blue".members in the Team object changes from null to an ArrayList.Team() has finished, so its variables are gone.withMember() has finished, so its variables are gone.t2.members(). It gets its own variables on the stack.members() has finished, so its variables are gone.members(). It gets its own variables on the stack.members() has finished, so its variables are gone.[ana] [ana, ben].Answer: So the caller cannot change it afterwards. Defensive copying.
Answer: Returns a new string. Like withMember.
← Nested, Inner and Anonymous Classes · try-with-resources and AutoCloseable →