Java Reference
In-Depth Information
another class organizes those objects in a particular way. For example, a sorted list of names
maintains the names in alphabetical order. If a client can alter a name in the list, it can destroy the
order of the list.
This chapter looks at two strategies that prevent this problem. The first one simply requires a
client to place into a collection only objects that cannot be altered. The second strategy requires the
collection to make a copy, or clone, of any object that a client adds to it. With this technique, the
client has no reference to the copy and so cannot change it. In describing this approach, we discuss
how to write methods that make clones of objects.
Mutable and Immutable Objects
30.1
Many of the classes you have studied so far have private data fields and public methods that either
look at or change these fields. As you know, such methods are called accessor methods and mutator
methods—or, alternatively, get and set methods. An object that belongs to a class that has public
mutator methods is said to be mutable—as we mentioned in Chapter 10—because the client can use
the set methods to change the values of the object's data fields. For example, you saw the class Name
of two-part names in Segment B.16 of Appendix B. It has the following two data fields:
private String first; // first name
private String last; // last name
VideoNote
Mutable and
immutable objects
To change these fields, the class has the mutator methods setFirst and setLast . To look at the
fields, it has the accessor methods getFirst and getLast .
Note: A mutable object belongs to a class that has mutator (set) methods for its data fields.
30.2
Let's use this class to create an object for Chris Coffee by writing the following Java statement:
Name chris = new Name("Chris", "Coffee");
Figure 30-1 illustrates this object and the reference variable chris .
FIGURE 30-1
An object and its reference variable chris
"Chris" "Coffee"
chris
Now suppose we create a list and then add chris to the list by writing
ListInterface<Name> nameList = new LList<Name>();
nameList.add(1, chris);
Since chris is a mutable object, we can change its data fields by writing, for example,
chris.setLast("Smith");
After this change, the object chris represents the name Chris Smith . Nothing is surprising here.
What might be surprising, however, is that the list has changed! That's right: If we retrieve the first
item in the list by writing, for instance,
System.out.println(nameList.getEntry(1));
we will get Chris Smith instead of Chris Coffee .
 
Search WWH ::




Custom Search