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

Answer:

Of course. Playing with things always helps to understand them.


Playful Program

Here is the program, just as before, but with some statements added to show what is going on.

import java.util.* ;

class Entry
{
  private String name;
  private String number;

  // constructor
  public Entry( String n, String num )
  {
    name = n; number = num;
  }

  // methods
  public String getName()
  {
    return name ;
  }

  public String getNumber()
  {
    return number ;
  }

  public boolean equals( Object other )
  {
   
    System.out.print  ("    Compare " + other + " To " + this );
    System.out.println(" Result: " +  name.equals( ((Entry)other).name ) );
    return getName().equals( ((Entry)other).getName() );
  }

  public String toString()
  {
    return "Name: " + getName() + "; Number: " + getNumber() ;
  }
 
}

public class PhoneBookTest
{
  public static void main ( String[] args)
  {
    ArrayList<Entry> phone = new ArrayList<Entry>();

    phone.add( new Entry( "Amy", "123-4567") );
    phone.add( new Entry( "Bob", "123-6780") );
    phone.add( new Entry( "Hal", "789-1234") );
    phone.add( new Entry( "Deb", "789-4457") );
    phone.add( new Entry( "Zoe", "446-0210") );

    // Look for Hal in phone. The indexOf() method uses the
    // equals(Object) method of each object in the list.
    // 

    System.out.println("Begin Search" ); 
    Entry target = new Entry( "Hal", null );
    
    int spot = phone.indexOf( target ) ;
    System.out.println("End Search" );

    System.out.println( "indexOf returns: " + spot ) ;
  }
}

Copy the program to a file and run it. Play with it for a while.


QUESTION 28:

Could the program be altered so that it searches for a name entered by the user?

(It would be good practice for you to do this before you go on.)


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