It will find a syntax error because name
is not
an instance variable of Object
.
These ideas are a little bit confusing. It is a good idea to write a test program to see if things work as expected:
import java.util.* ; import java.io.*; class Entry { String name; String number; // constructor Entry( String n, String num ) { name = n; number = num; } // methods public boolean equals( Object other ) { return name.equals( ((Entry)other).name ); } public String toString() { return "Name: " + name + " Number: " + number; } } class PhoneBookTest { public static void main ( String[] args) throws IOException { Vector phone = new Vector( 10 ); phone.addElement( new Entry( "Amy", "123-4567") ); phone.addElement( new Entry( "Bob", "123-6780") ); phone.addElement( new Entry( "Hal", "789-1234") ); phone.addElement( new Entry( "Deb", "789-4457") ); phone.addElement( new Entry( "Zoe", "446-0210") ); // look for Hal in phone using our equals() method int spot = phone.indexOf( new Entry( "Hal", "") ) ; System.out.println( "indexOf returns: " + spot ) ; } }
The entry we build as the target of the search has an empty
string for the phone number.
The equals()
method will compare it with entries
that have a non-empty phone number.
But equals()
is written to look only at the
name
of the two entries, so this is OK.