Java Reference
In-Depth Information
// make an alphabetical list of names as students enter a room
ListInterface<String> alphaList = new AList<String>();
alphaList.add(1, "Amy"); // Amy
alphaList.add(2, "Ellen"); // Amy Ellen
alphaList.add(2, "Bob"); // Amy Bob Ellen
alphaList.add(3, "Drew"); // Amy Bob Drew Ellen
alphaList.add(1, "Aaron"); // Aaron Amy Bob Drew Ellen
alphaList.add(4, "Carol"); // Aaron Amy Bob Carol Drew Ellen
After initially adding Amy to the beginning of the list and Ellen to the end of the list (at posi-
tion 2), the professor inserts
Bob between Amy and Ellen at position 2
Drew between Bob and Ellen at position 3
Aaron before Amy at position 1
Carol between Bob and Drew at position 4
Recall that this technique of inserting each name into a collection of alphabetized names is called
an insertion sort.
If we now remove the entry at position 4—Carol—by writing
alphaList.remove(4);
Drew and Ellen will then be at positions 4 and 5, respectively. Thus, alphaList.getEntry(4)
would return a reference to Drew.
Finally, suppose that we want to replace a name in this list. We cannot replace a name with just any
name and expect that the list will remain in alphabetical order. Replacing Bob with Ben by writing
alphaList.replace(3, "Ben");
would maintain alphabetical order, but replacing Bob with Nancy would not. The list's alphabetical
order resulted from our original decisions about where to add names to the list. The order did not
come about automatically as a result of list operations. That is, the client, not the list, maintained
the order. We could, however, design an ADT that maintains its data in alphabetical order. You will
see an example of such an ADT in Chapter 16.
Question 4 Suppose that alphaList contains a list of the four names Amy, Ellen, Bob, and
Drew as strings. Write Java statements that swap Ellen and Bob and that then swap Ellen
and Drew so that the list will be in alphabetical order.
12.10
Example. Let's look at a list of objects that are not strings. Suppose that we have the class Name
from Appendix B that represents a person's first and last names. The following statements indicate
how we could make a list of the names Amy Smith, Tina Drexel, and Robert Jones:
// make a list of names as you think of them
ListInterface<Name> nameList = new AList<Name>();
Name amy = new Name("Amy", "Smith");
nameList.add(amy);
nameList.add( new Name("Tina", "Drexel"));
nameList.add( new Name("Robert", "Jones"));
Now let's retrieve the name that is second in the list, Tina Drexel:
Name secondName = nameList.getEntry(2);
The definition of getEntry declares its return type as T , the generic type of the entries in the list.
This type for nameList is Name , so getEntry returns a Name object.
Search WWH ::




Custom Search