PhoneEntry[] phoneBook = new PhoneEntry[ 5 ] ;
phoneBook
is an array of 5 references to phoneEntry
objects.
But so far there are no phoneEntry
objects and every cell
of phoneBook
is null
.
In a practical application the data for the phone book would be read in from a disk file, and ordinarily there would be thousands of entries. But, for this example, entries are "hard coded" into the constuctor. (A programming exercise has you improve on this.)
class PhoneEntry { private String name; // name of a person private String phone; // their phone number public PhoneEntry( String n, String p ) { name = n; phone = p; } public String getName() {return name;} public String getPhone() {return phone;} } class PhoneBook { private PhoneEntry[] phoneBook; public PhoneBook() // constructor { phoneBook = new PhoneEntry[ 5 ] ; phoneBook[0] = new PhoneEntry( "James Barclay", "(418) 665-1223" ); phoneBook[1] = new PhoneEntry( "Grace Dunbar", "(860) 399-3044" ); phoneBook[2] = null; phoneBook[3] = new PhoneEntry( "Violet Smith", "(312) 223-1937" ); phoneBook[4] = new PhoneEntry( "John Wood", "(913) 883-2874" ); } public PhoneEntry search( String targetName ) { . . . // Use linear search to find targetName } }
Can the linear search algorithm be used on a partially full array?