Lecture 23
c
°2005 Felleisen, Proulx, et. al.
23 Mutating ArrayList
Introduction
We would like to design the program that will allow us to keep track of
our friends’ phone numbers. As the time goes on, we may want to add
new friends to the list, we may want to change someone’s phone number
as they find a new job. We will make several such phone lists, for example
a family list, school friends, friends from the sports club, the acm friends,
etc. Of course, some people may be listed in several of these lists. There are
two problems we want to address. The first problem is that if a phone num-
ber for a person is changed, then one update operation should change the
phone number in all lists. The second problem is that all of these lists are
accessed by various programs and devices that have a reference to some,
or all of these phone lists. Therefore, adding a new entry to a phone list
cannot produce a new list the way we programmed so far. Instead, it needs
to modify (mutate) an existing list.
Here is an example of the information we want to represent:
Friends: Pat 2345, Jan 1398, Kerry 6783
Family: Terry 8877, Alex 6655, Randy 5566
SwimClub: Terry 8877, Pat 2345, Jan 1398
PhoneLists: Friends, Family, SwimClub
We define a class PhoneRec to represent a phone record, an ArrayList for
each of the three phone lists and an ArrayList to represent the list of phone
lists. We omit the definition of the class PhoneRec and show the definition
for only first three people in our lists, assuming the rest of them are defined
in a similar way. The complete examples of data then become:
PhoneRec pat = new PhoneRec("Pat", 2345);
PhoneRec jan = new PhoneRec("Jan", 1398);
PhoneRec kerry = new PhoneRec("Kerry", 6783);
. . .
ArrayList friends = new ArrayList();
ArrayList family = new ArrayList();
ArrayList swimClub = new ArrayList();
ArrayList phoneLists = new ArrayList();
1