equals()
method or the compareTo()
method. Here's how to use each method:equals()
method is used to check if two objects are equal in value. It returns a boolean value true
if the objects are equal and false
otherwise. By default, the equals()
method compares the memory addresses of the objects. To compare the contents of the objects instead, you need to override the equals()
method in the class definition.Person
with two instance variables name
and age
. We can override the equals()
method in the Person
class to compare the name
and age
variables :public class Person {
private String name;
private int age;
// constructor, getter and setter methods
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (!(o instanceof Person)) {
return false;
}
Person p = (Person) o;
return name.equals(p.name) && age == p.age;
}
}
equals()
method, we first check if the objects are the same using the ==
operator. If they are, we return true
. We then check if the object is an instance of the Person
class. If it is not, we return false
.Person
object and compare the name
and age
variables using the equals()
method and the ==
operator, respectively.ompareTo()
method is used to compare two objects and returns an integer value that indicates the relationship between the objects. It returns a negative integer if the first object is less than the second object, zero if they are equal, and a positive integer if the first object is greater than the second object.compareTo()
method, the class of the objects being compared must implement the Comparable
interface and define the compareTo()
method in the class definition.Person
with an instance variable age
. We can implement the Comparable
interface in the Person
class to compare the ages of two Person
objects:public class Person implements Comparable<Person> {
private String name;
private int age;
// constructor, getter and setter methods
@Override
public int compareTo(Person p) {
return Integer.compare(age, p.age);
}
}
compareTo()
method, we compare the age
variable of the two Person
objects using the Integer.compare()
method, which returns a negative integer if the age of the first object is less than the age of the second object, zero if they are equal, and a positive integer if the age of the first object is greater than the age of the second object.