How can you compare the values of two object properties in Java?
In Java, we can compare the attribute values of two objects by overriding the equals() method. The equals() method is a method in the Object class, and all classes inherit from the Object class, so it can be overridden in custom classes.
Here is an example that demonstrates comparing the attribute values of two Person objects by overriding the equals() method.
public class Person {
private String name;
private int age;
// 构造方法和getter/setter省略
@Override
public boolean equals(Object obj) {
// 首先判断两个对象是否引用同一个内存地址
if (this == obj) {
return true;
}
// 判断obj是否为Person类的实例
if (obj == null || getClass() != obj.getClass()) {
return false;
}
// 将obj转换为Person对象
Person person = (Person) obj;
// 比较name和age属性值是否相等
return age == person.age && Objects.equals(name, person.name);
}
}
In the given example, we first check if two objects reference the same memory address. If they do, we return true. Then we check if obj is an instance of the Person class. If not, we return false. Finally, we convert obj into a Person object and compare the values of the name and age properties to check if they are equal.
In addition, to better compare the values of attributes, we can use the Objects.equals() method to compare whether the values of two objects are equal, instead of using == to compare string type attribute values. This is because the Objects.equals() method will first check if the parameters are null, and then call the object’s equals() method to make the comparison, avoiding the occurrence of null pointer exceptions.