Yes, of course. In fact, it can be simplified.
Linear search can be simplified if it does not have to
test each array entry for null
.
Here is some code with search()
partially finished:
class PhoneEntry { String name; // name of a person String phone; // their phone number . . . . . } class PhoneBook { PhoneEntry[] phoneBook; PhoneBook() // constructor { phoneBook = new PhoneEntry[ 5 ] ; . . . . . . } PhoneEntry search( String targetName ) { // use linear search to find the targetName for ( int j=0; j < phoneBook.__________; j++ ) { if ( phoneBook[ j ].name.equals( ____________ ) ) return phoneBook[ j ]; } return null; } }
Recall that search()
returns
either a reference to the correct entry,
or null
if the entry could not be found.