Yes. The method combines several steps into one statement.
These ideas might be confusing. Here is a program that shows how how the pieces fit together. Copy this program to a file, compile it, and run it:
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 )
{
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.
Entry target = new Entry( "Hal", null );
int spot = phone.indexOf( target ) ;
System.out.println( "indexOf returns: " + spot ) ;
}
}
phone is a list of Entry references.
The program searches that list for "Hal" .
It does so by creating a target
Entry with "Hal" for the name, but null for the phone number.
Then the indexOf() method of phone looks for a match.
The indexOf() method uses equals()
to compare successive objects
in the list with the target object.
Because equals() looks only at the
name of the two entries,
the null in the target object does not matter.
What will the program write?