ArrayLists and Iterators

24. Testing for Equality


Answer:

We need the equals(Object) method so the ArrayList method indexOf() can be used to search.

Testing for Equality

Examine the equals(Object) method:

              
class Entry
{
  private String name;
  private String number;

  . . . . .

  // Compare the name of this Entry with that of some other object
  public boolean equals( Object other )
  {
    String otherName = ((Entry)other).getName();  // Get the name in the other object.
    return name.equals( otherName );              // Compare the name in this object 
                                                  // with that in the other object.
  }

  . . . . . 
} 

All classes have an equals(Object) method because it is defined in the Object class and all other classes descend from that class.

It might be helpful to look at the Java documentation for class Object at this point: Object

So all classes have the equals(Object) method by inheritance. However, most classes override it with a method better suited for their own purpose.

The method expects a parameter of type Object. This says that the method works with a reference to any type of object. However, our application must compare two Entry objects with each other. (One entry holds the name we are searching for; the other is an element of the ArrayList.) The following

String otherName = ((Entry)other).getName(); 

uses a type cast to tell the compiler that other is a reference to an Entry. This must be done to access the getName() method of the Entry object.

Then the name from the other object is compared to the name in the object that contains the equals() method:

return name.equals( otherName );

If the two names are the same, the method returns true.


Question 24:

Would the following equals() method work as well?

    class Entry { . . . . . public boolean equals( Object other ) { return name.equals( other.getName() ); } . . . . . }