1

I saw two different version this code, one from Java Oralce and the other from Youtube. The only difference between the two version is the parameter type of equals() method. One of the is equals(Object o) whereas the other is equals(Name o). I was just wondering if there is any meaningful difference between the two version? if yes, what implication does it have? Thanks for any help I could get!

public class Name implements Comparable<Name> {
    private final String firstName, lastName;

    public Name(String firstName, String lastName) {
        if (firstName == null || lastName == null)
            throw new NullPointerException();
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String firstName() { return firstName; }
    public String lastName()  { return lastName;  }

    public boolean equals(Object o) {
        if (!(o instanceof Name))
            return false;
        Name n = (Name) o;
        return n.firstName.equals(firstName) && n.lastName.equals(lastName);
    }

    public int hashCode() {
        return 31*firstName.hashCode() + lastName.hashCode();
    }

    public String toString() {
    return firstName + " " + lastName;
    }

    public int compareTo(Name n) {
        int lastCmp = lastName.compareTo(n.lastName);
        return (lastCmp != 0 ? lastCmp : firstName.compareTo(n.firstName));
    }
}
  • 2
    To override `equals`, the parameter **must** be `Object`, not something else. Otherwise, you're *overloading*, not overriding, and the wrong `equals` will get called in a variety of contexts. The linked question and its answers (and several others here on SO) have details. – T.J. Crowder Mar 19 '16 at 12:41

1 Answers1

3

equals(Object o) overrides Object's equals method while equals(Name o) does not. Therefore, if the Name class is used with some class that uses Object's equals (for example HashSet<Name>, ArrayList<Name>, etc...) you should implement equals(Object o) if you want to override the default logic of how to determine if two objects are equal to each other (the default behavior is that a.equals(b) if a==b).

For example, the following code will produce the output 2 if equals(Name o) is implemented (since according to the default implementation of equals(Object o), the two objects added to the Set are not equal to each other) and 1 if equals(Object o) is implemented as in your code sample (since according to your implementation of equals(Object o), the two objects added to the Set are equal to each other and HashSet prevents duplicates).

Set<Name> names = new HashSet<>();
names.add(new Name("John","Smith"));
names.add(new Name("John","Smith"));
System.out.println(names.size());
Eran
  • 387,369
  • 54
  • 702
  • 768