Java – Use the equals method to test the equality of objects in Java

Use the equals method to test the equality of objects in Java… here is a solution to the problem.

Use the equals method to test the equality of objects in Java

I would like to ask a question about using the equals method to test object equality in Java.

I am a beginner in Java and am currently studying the Dummies Java 9-in-1 book.

I wrote the following code to check if the two Employee objects are equal:

public class TestEquality2 {
    public static void main (String [] args) {
        Employee emp1 = new Employee ("Martinez", "Anthony");
        Employee emp2 = new Employee ("Martinez", "Anthony");
        if (emp1.equals(emp2))
            System.out.println("These employees are the same");
        else
            System.out.println("These employees are different.");
    }
}

class Employee {
    private String firstName;
    private String lastName;

public Employee (String firstName, String lastName) {
        this.lastName = lastName;
        this.firstName = firstName;
    }

public String getLastName() {
        return this.lastName;
    }

public String getFirstName() {
        return this.firstName;
    }

public boolean equals (Object obj) {
         an object must equal itself
        if (this == obj)
            return true;

 no object equals null
        if (this == null)
            return false;

if (this.getClass() != obj.getClass())
            return false;

 Cast to an employee, then compare the fields
        Employee emp = (Employee) obj;
         is this the string's equals method?
        return this.lastName.equals(emp.getLastName()) && this.firstName.equals(emp.getFirstName());
    }
}

The focus is on the last of the equals(Object obj) method.

Based on the code, I overridden the default Object equals() method and provided my own design, but I’m confused here:

return this.lastName.equals(emp.getLastName()) && this.firstName.equals(emp.getFirstName());

I

know lastName is a string, but the equals() method I’m using here is equals() String or the method I just defined? If it’s the latter, I know I’ll create a recursive case, and although I’m sure I’m using String equals() I’d like to clarify to get it done.

Solution

lastName is a String, so calling this.lastName.equals(emp.getLastName()) will use the String implementation of the equals method. Of course, the same goes for the comparison of names.

Related Problems and Solutions