Java Reference
In-Depth Information
Code 12.1
continued
The AddressBook
class
public ContactDetails[] search(String keyPrefix)
{
List<ContactDetails> matches =
new LinkedList<ContactDetails>();
// Find keys that are equal-to or greater-than the prefix.
SortedMap<String, ContactDetails> tail =
book.tailMap(keyPrefix);
Iterator<String> it = tail.keySet().iterator();
boolean endOfSearch = false ;
while (!endOfSearch && it.hasNext()) {
String key = it.next();
if (key.startsWith(keyPrefix)) {
matches.add(book.get(key));
}
else {
// As the list is sorted, no more will be found.
endOfSearch = true ;
}
}
ContactDetails[] results =
new ContactDetails[matches.size()];
matches.toArray(results);
return results;
}
/**
* Return the number of entries currently in the
* address book.
* @return The number of entries.
*/
public int getNumberOfEntries()
{
return numberOfEntries;
}
/**
* Remove the entry with the given key from the address book.
* @param key One of the keys of the entry to be removed.
*/
public void removeDetails(String key)
{
ContactDetails details = book.get(key);
book.remove(details.getName());
book.remove(details.getPhone());
numberOfEntries--;
}
Search WWH ::




Custom Search