The `equals()` Method in Java
In Java, the equals()
method is used to determine whether two objects are equal or not. This method is defined in the Object
class, which is the root of the Java class hierarchy, and is therefore inherited by all Java classes.
Here is an example of how the equals()
method might be used:
String str1 = "hello";
String str2 = "hello";
String str3 = new String("hello");
System.out.println(str1.equals(str2)); // true
System.out.println(str1.equals(str3)); // true
In this example, the equals()
method is used to compare the contents of two String
objects, str1
and str2
, and two String
objects, str1
and str3
. The equals()
method returns true
in both cases, indicating that the objects are equal.
By default, the equals()
method compares the objects based on their memory addresses, which means that two objects are considered equal only if they are stored at the same memory location. However, you can override the equals()
method in your own classes to provide a custom implementation that compares the objects based on their contents or other criteria.
For example, if you have a Person
class with name
and age
fields, you might override the equals()
method to compare two Person
objects based on their name
and age
fields:
class Person {
String name;
int age;
@Override
public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof Person)) return false;
Person p = (Person) o;
return p.name.equals(name) && p.age == age;
}
}
Now, you can use the equals()
method to compare two Person
objects based on their name
and age
fields:
Person p1 = new Person("John", 30);
Person p2 = new Person("John", 30);
Person p3 = new Person("Jane", 25);
System.out.println(p1.equals(p2)); // true
System.out.println(p1.equals(p3)); // false
It's important to note that the equals()
method should be used to compare the contents of objects, rather than the objects themselves. In other words, the equals()
method should return true
if the contents of two objects are equal, even if the objects are stored at different memory locations.