Java Reference
In-Depth Information
30.3
How can it be that the list, which we created before changing the name, contains the changed name?
Remember that in Java, the list contains references to the actual objects that the client places in it. So
the list has a reference to its first item, but so does the client, since it has the variable chris , as
Figure 30-2a shows.
FIGURE 30-2
An object in the list nameList (a) initially; (b) after the refer-
ence variable chris is used to change it
(a)
chris
"Chris" "Coffee"
nameList
(b)
chris
"Chris" "Smith"
nameList
When we altered the object by executing
chris.setLast("Smith");
we changed the one and only copy of the object, as Figure 30-2b shows. Since the list still refer-
ences that object, nameList.getEntry(1) returns a reference to the object. This aspect of Java can
be a convenient way for the client to alter the objects it has placed in a list.
Note: When a client creates a mutable object and adds it to an ADT list, only one copy of
the object ordinarily exists. Thus, if the client alters the object, the list changes. Ideally, the
client will use the replace operation to revise an entry in the list, but we cannot force the
client to do so.
30.4
The ability to alter mutable objects in a collection can permit a client to destroy the collection's integ-
rity. For example, suppose that we create a sorted list of names instead of a list of names. If we write
Name jesse = new Name("Jesse", "Java");
Name rob = new Name("Rob", "Bean");
SortedListInterface<Name> alphaList = new SortedList<Name>();
alphaList.add(jesse);
alphaList.add(rob);
we would get the sorted list
Rob Bean
Jesse Java
 
Search WWH ::




Custom Search