Sub topic 10
Defensive Copying and Mutable State
An object is a value created from a class, which is a blueprint for creating objects. An object’s state is the data it holds. Mutable state is data that can change after it is created.
A reference is a value that points to an object. In Java, two variables can hold references to the same object. If that object is mutable, changes made through one reference are visible through the other.
This can be a problem even when a field, or a variable stored in an object, is private. A private field cannot be accessed directly from outside its class. But if the field points to a mutable object, outside code might still have a reference to that same object.
Copy on the way in and out
A defensive copy is a separate copy made to prevent unwanted changes. For a mutable value, such as a list, make a copy at each boundary:
- Copy input before storing it. This stops the caller from changing the stored list later.
- Copy output before returning it. This stops the caller from changing the stored list through the returned value.
A list is an ordered group of values. A caller is the code that uses a method or creates an object. A method is an operation an object can perform.
Try a playlist
A constructor is code that sets up a new object. The Playlist constructor below copies the list it receives. The getSongs method returns another copy.
Save this program as Main.java:
import java.util.ArrayList;
import java.util.List;
class Playlist {
private final List<String> songs;
public Playlist(List<String> songs) {
this.songs = new ArrayList<>(songs);
}
public List<String> getSongs() {
return new ArrayList<>(songs);
}
}
public class Main {
public static void main(String[] args) {
List<String> original = new ArrayList<>();
original.add("First Song");
Playlist playlist = new Playlist(original);
original.add("Second Song");
List<String> returned = playlist.getSongs();
returned.add("Third Song");
System.out.println("Original: " + original);
System.out.println("Returned: " + returned);
System.out.println("Playlist: " + playlist.getSongs());
}
}Run it from the folder containing the file:
javac Main.java
java MainThe output is:
Original: [First Song, Second Song]
Returned: [First Song, Third Song]
Playlist: [First Song]The constructor copied original when it contained only First Song. Adding Second Song later changed the original list, not the playlist’s list.
Next, getSongs returned a new list. Adding Third Song changed that returned list, not the playlist’s list. The final call to getSongs shows that the playlist still contains only First Song.
The returned list is a snapshot: it shows the playlist contents at the time of the call. Changing it does not update the playlist. If a playlist needs to let callers add songs, it can provide a method for that action instead.
The final word on songs means the field cannot be made to point to a different list after it is set. It does not stop the list itself from changing. The copies are what keep outside code from changing this list.
Watch for shared items
Copying a list this way makes a shallow copy. A shallow copy creates a new list but does not create new copies of the items inside it.
That is enough for this example because String objects are immutable: their text cannot be changed after creation. The lists can safely share references to the same strings.
Suppose the list held mutable Song objects instead, and each song had a title that could change. Both lists would still refer to the same songs. A caller could change a song’s title through either list.
To protect that state, copy each mutable song on input and output too. If a song contains other mutable objects, those may also need copies. Another option is to use immutable song objects.
Copies use extra time and memory, especially for large lists. Make them where they protect state from unwanted changes, and be clear that callers receive a separate list.
Check your understanding
Exercise
What could happen if the constructor stored original directly, even though getSongs still returned a copy?
Show answer
Adding a song to original could also change the playlist, because both would refer to the same list.
Exercise
Why might copying a list of mutable songs still leave the playlist open to changes?
Show answer
The copied list can still refer to the same song objects, so a caller could change those objects.