Junior — Middle
What methods can be used to determine the equality of two objects in Java?
sobes.tech AI
Answer from AI
In Java, equality of two objects can be determined in several ways:
-
Operator
==— compares references to objects, i.e., checks whether both variables point to the same object in memory. -
Method
equals()— intended for checking logical equality of objects. By default (in theObjectclass), it behaves like==, but it is often overridden to compare the contents of objects.
Example of overriding equals():
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Person other = (Person) obj;
return age == other.age && name.equals(other.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
}
- Use of specialized methods or libraries — for example,
Objects.equals()for safe comparison consideringnull.
Important: when overriding equals(), you should also override hashCode() for correct operation in collections.