Middle
Given the following Java class class Person { String firstName; String lastName; Integer age; } Implement a standard method that compares two Person objects.
sobes.tech AI
Answer from AI
To compare two objects of the Person class, it is common to override the equals method and, preferably, the hashCode method. Here is an example implementation:
class Person {
String firstName;
String lastName;
Integer age;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return Objects.equals(firstName, person.firstName) &&
Objects.equals(lastName, person.lastName) &&
Objects.equals(age, person.age);
}
@Override
public int hashCode() {
return Objects.hash(firstName, lastName, age);
}
}
This uses the Objects class from java.util for convenient comparison and hash code calculation, taking into account possible null values.