It will find an error because getName()
is not
a method of Object
.
These ideas are a little bit confusing. Let us write a test program to see if things work as expected. You should be able to copy this program to a file, and compile, and run it.
import java.util.* ; class Entry { private String name; private String number; // constructor 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() ; } } 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. // int spot = phone.indexOf( new Entry( "Hal", null ) ) ; System.out.println( "indexOf returns: " + spot ) ; } }
The ArrayList
is declared to be a list of Entry
references.
The Entry
used as the target of the search has null for the phone number.
The equals()
method compares it with entries
in the list, which have a non-null phone number.
But equals()
is written to look only at the
name
of the two entries, so this is OK.
What will the program write?