go to previous page   go to home page   go to next page highlighting

Answer:

Yes, of course. You need to watch out for nulls, though.


Linear Search

Here is some code with search() partially finished:

search() returns either a reference to the correct entry, or null if the entry could not be found.


class PhoneEntry
{
  private String name;    // name of a person
  private String phone;   // their phone number
 
  . . . . . 
}

class PhoneBook
{ 
  private PhoneEntry[] phoneBook; 

  public PhoneBook()    // constructor
  {
    phoneBook = new PhoneEntry[ 5 ] ;

    . . . . . .
  }

  public PhoneEntry search( String targetName )  
  {
    // use linear search to find the targetName

    for ( int j=0; j < phoneBook.; j++ )
    {
      if ( phoneBook[ j ] != null && phoneBook[ j ].getName().equals( targetName ) )
        return phoneBook[ j ];
    }

    return null;
  }
}

Common Trick: Recall that && is a short-circuit operator. This means that as soon as it find a false, evaluation of the complete Boolean expression stops. Look at this expression:

phoneBook[ j ] != null && phoneBook[ j ].getName().equals( targetName )

If the j'th cell of phoneBook is null, the right side of the expression is not evaluated because the entire expression is false, no matter what.


QUESTION 13:

(Review: ) Say that phoneBook[ j ] != null is true. What possible values might the entire expression have?


go to previous page   go to home page   go to next page