|
The equals method defined in Object class compares two objects by comparing their references. Since the two object references are same only when they both point to essentially the same object, this kind of equality comparison is often not very useful. We say in chapter 13 how the wrapper and string class override this method to compare the contents of two objects to decide whether they are equal or not. Overriding this method is important in the context of collection framework as well. Many basic operations that collection performs need to compare the objects for equality. For instance, when you ask a collection to search an object, it does so by iterating over all its elements and comparing each element with the object you are supplying. It does this comparison using the equals() method. For instance, the indexOf() method of ArrayList looks like this:

Now if the class of elements you are storing in the ArraList override the equals() method to compare the objects based on their contents rather than comparing their references, you can successfully find the index. For example, the String class overrides the equals() method hence you can search a string with same content using the indexOf() or(using contains() which inturn call indexOf() method).
ArrayList names = new ArrayList();
names.add(“Eagle”);
names.add(“Phoenix”);
names.add(“Flamingo”);
String birdTofind = new String(“Flamingo”);
if(names.contains(birdTofind))
System.out.println(“Found it.”);
If the String class had not overridden the equals() method the string object pointed by birdTofind could have never found in the collection because the equals() method in Object class would return false for two string objects even if their contents are same.
Since you can store any type of objects in collections, you can store objects defined by your own class. Listing 14.2 illustrates a Bird class and stores Bird objects in ArraList Collection.

The Bird class does not override the equals() method. Hence it inherits it from Object class which compares the object references. When you invoke names.contains(birdTofind) methods, the collection object goes over all the elements and compare the references with birdTofind. Now even if the third element in names is a Bird object with same state as the Bird Object reference by birdToFind, they are two distinct Bird objects. Hence their references are not same. Therefore equals() will return false. But if you want the Bird object to be found by comparing the object content, you must override the equals() method.