Sub topic 10
Defensive Copying and Mutable State
A private field can still be changed by outside code if it holds an object that the outside code can also reach. This matters when the object is mutable: its contents can change after it is created.
A defensive copy is a separate copy made to prevent unwanted changes through a shared object. In this chapter, you will use defensive copies to protect a playlist’s list of songs. You will also see why copying a list is not always enough.
The problem with sharing a list
An object’s state is the data it holds. A playlist might keep its state in a list of song titles. The playlist may want to control which titles appear in that list.
A reference is a value that lets code find an object. Two parts of a program can hold references to the same list. If either part changes that list, the other part sees the change.
Suppose a playlist constructor takes a list from its caller. The caller is the code that creates or uses the playlist. If the constructor stores the caller’s list directly, both the caller and the playlist can change the same list.
The same problem can happen in the other direction. If a method returns the playlist’s own list, the caller can change it without asking the playlist.
The arrows show copying, not ongoing connections. After each copy, adding or removing an item in one list does not add or remove it in the other.
Copy a list on the way in and out
The following program makes a separate list in the constructor. Its getter, a method that returns a value, makes another separate list each time it is called.
Save the program as Main.java.
import java.util.ArrayList;
import java.util.Arrays;
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> input = new ArrayList<>(
Arrays.asList("Blue Sky", "Night Train")
);
Playlist playlist = new Playlist(input);
input.add("Extra Song");
System.out.println("Input: " + input);
System.out.println("Playlist: " + playlist.getSongs());
List<String> result = playlist.getSongs();
result.clear();
System.out.println("Cleared result: " + result);
System.out.println("Playlist: " + playlist.getSongs());
}
}Compile and run it from the folder that contains Main.java:
javac Main.java
java MainThe output is:
Input: [Blue Sky, Night Train, Extra Song]
Playlist: [Blue Sky, Night Train]
Cleared result: []
Playlist: [Blue Sky, Night Train]The constructor creates a new list with the same items as the input list. Adding “Extra Song” to the input changes only the input.
Later, the getter creates another new list. Calling clear on that returned list removes its items, but it does not clear the playlist’s list.
This example has no method for adding songs to the playlist after construction. A class that needs that feature can provide a method for it. That method can check a title before adding it to the private list.
Why both copies matter
Copying only at one boundary leaves the other boundary open.
| Where the copy is missing | What outside code can do |
|---|---|
| Constructor | Change the input list after creating the playlist. |
| Getter | Change the list returned by the getter and thereby change the playlist’s list. |
| Neither is missing | Change its own input or returned lists without changing the playlist’s list. |
Think of a returned copy as a snapshot: it shows the contents at the time of the copy. If the playlist later changes its own list, an older returned copy does not update. Changing that old copy does not update the playlist either.
A copy is not the same as a validity check. The playlist example assumes the input list is not null. It also allows null items and empty titles. If a playlist must reject those values, its constructor and any methods that add songs need to check them. Make a separate list first, then check the values that the playlist will keep.
List copies and their items
The playlist example works well because its items are strings. A string is immutable: once created, its contents cannot be changed. Each list is separate, and sharing the string objects between the lists is safe.
A new list normally copies its item references, not the items themselves. This is called a shallow copy. It gives you a separate list, but both lists can still refer to the same mutable items.
For example, imagine a list of Song objects whose titles can be changed. A shallow copy of that list stops the caller from adding or removing songs in the original list. It does not stop the caller from changing the title of a Song that both lists share.
A deep copy also copies the mutable items that need protection. The next example makes a new Song for each item, both when an album is created and when its songs are requested.
Save this program as AlbumDemo.java.
import java.util.ArrayList;
import java.util.List;
class Song {
private String title;
public Song(String title) {
this.title = title;
}
public Song(Song other) {
this.title = other.title;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
class Album {
private final List<Song> songs;
public Album(List<Song> songs) {
this.songs = copySongs(songs);
}
public List<Song> getSongs() {
return copySongs(songs);
}
private static List<Song> copySongs(List<Song> source) {
List<Song> copy = new ArrayList<>();
for (Song song : source) {
copy.add(new Song(song));
}
return copy;
}
}
public class AlbumDemo {
public static void main(String[] args) {
Song original = new Song("Blue Sky");
List<Song> input = new ArrayList<>();
input.add(original);
Album album = new Album(input);
original.setTitle("Changed outside");
List<Song> result = album.getSongs();
result.get(0).setTitle("Changed in result");
result.clear();
System.out.println(album.getSongs().get(0).getTitle());
}
}Compile and run it:
javac AlbumDemo.java
java AlbumDemoThe program prints “Blue Sky”. Changing the original Song does not change the album’s Song. Changing and removing the Song in the returned list does not change it either.
The constructor in Song that accepts another Song is a copy constructor: it creates a new Song using data from an existing one. Its title is a string, so the two Song objects can safely share that string.
This example assumes the input list and its Song items are not null. It also copies only the title because that is all a Song contains. If Song later holds another mutable object, the copy constructor may need to copy that object too.
An unmodifiable list is not always a copy
An unmodifiable list is a list that does not allow callers to add, remove, or replace its items through that list. It can be useful, but check what it protects.
Java’s Collections.unmodifiableList can give a caller an unmodifiable view of a list. A view is another way to see an existing object, not a separate copy of its contents. If the original list changes, the view shows those changes. The caller cannot change the list through the view, but the view is not a snapshot.
Also, preventing changes to the list does not make its items immutable. If an unmodifiable list contains mutable Song objects, a caller may still be able to change a Song.
Choose based on what callers need:
- Use a copy when callers need a snapshot they can change without affecting the original.
- Use an unmodifiable view when callers should see later list changes but should not add or remove items through the view.
- Copy mutable items as well when callers must not be able to change the original items.
What to look for in your own classes
Lists are not the only mutable values that can be shared. Arrays, for example, hold a fixed number of items, but their items can still be replaced. A class that stores or returns an array may need to copy it too.
Check each place where a mutable object crosses the class boundary:
- When an object comes in, ask whether the caller can still change it.
- When an object goes out, ask whether the caller can change the class’s state through it.
- If the object contains other mutable objects, ask whether those need copies too.
- Check whether the class needs to reject invalid values as well as copy them.
Copying takes time and uses memory, especially for large lists or deep copies. Returning a fresh copy on every getter call may be more work than a program needs. Decide what callers are allowed to observe and change, then choose a way to provide it.
Finally, copying alone does not make a class safe for use by several threads at once. A thread is a path of work in a running program. If one thread changes a list while another copies it, the program needs additional coordination.
Practice
Exercise
A constructor stores the caller's list directly, but its getter returns a copy. Can the caller still change the object's list?
Show answer
Yes. The caller can change the original list it passed to the constructor. The constructor should copy that list too.
Exercise
A new list contains the same mutable Song objects as the original list. Does changing a Song in the new list affect the original list's Song?
Show answer
Yes. The lists are separate, but they hold references to the same Song objects. Copy the songs too if they must be protected.
Exercise
Why is a shallow copy enough for the playlist of string titles?
Show answer
The lists are separate, and strings are immutable. A caller cannot change the contents of a shared string.
Exercise
If an unmodifiable view is returned, can it show a later change made to the original list?
Show answer
Yes. A view sees the original list; it is not a separate snapshot.