// The Science of Computing PhoneEntry class. // History: // August 2003 -- Created by Greg Scragg. // October 2003 -- updates to several methods by GWS // April 2004 -- Documentation cleaned up and code debugged by Doug Baldwin. Also // added a "hashcode" method so that this class would meet the requirement // that objects that are equal according to the "equals" message have equal // hash codes (per Sun's documentation on Object.equals and Object.hashcode). // Made phone entries implement serializable so that data structures that contain // them can be written to and read from files. package geneseo.cs.sc; import java.io.Serializable; /** * Represents entries in a simple telephone directory, with each entry containing a * person's name, address, and telephone number. *
This class is intended a simple model for "record" objects that can be * stored in collections such as lists or trees. This class was created to support * the text Algorithms & Data Structures: The Science of Computing by * Doug Baldwin and Greg Scragg. All references herein to "the text" refer to * that book. */ public class PhoneEntry implements Comparable, Serializable { /** * The name of the person described by a telephone entry. Comparisons between * telephone entries are based on this field. */ public String name; /** * The street address for the person described by a telephone entry. */ public String address; /** * The telephone number for the person described by a telephone entry. */ public String phone; /** * Initialize a telephone book entry with a person's name, address, and * telephone number. For example *
PhoneEntry p = new PhoneEntry( "Sue", "1 Main St", "123-4567" );
if ( entry1.compareTo(entry2) < 0 ) ...
secondEntry
's; 0 if the names are equal; a positive number
* if this entry's name is greater than secondEntry
's.
*/
public int compareTo(Object secondEntry) {
return this.name.compareTo( ((PhoneEntry)secondEntry).name );
}
/**
* Determine whether two telephone entries are the same. Entries are considered
* equal if their name fields are the same. For example
* if ( entry1.equals(entry2) ) ...
int code = entry.hashCode();
See chapter 14 of Algorithms and Data Structures: The Science of * Computing for information on what hash codes are and why one uses * them.
* @return The hash code computed for this telephone entry. */ public int hashCode() { return name.hashCode(); } /** * Create a string representation of a telephone book entry. For example *String text = entry.toString();