要比较包含两个其他对象引用的对象,可以使用以下解决方法:
public class MyObject {
private Object obj1;
private Object obj2;
// constructors, getters and setters
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MyObject myObject = (MyObject) o;
if (obj1 != null ? !obj1.equals(myObject.obj1) : myObject.obj1 != null) return false;
return obj2 != null ? obj2.equals(myObject.obj2) : myObject.obj2 == null;
}
}
java.util.Objects
类中的equals()方法来比较两个对象的属性是否相等。import java.util.Objects;
public class MyObject {
private Object obj1;
private Object obj2;
// constructors, getters and setters
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MyObject myObject = (MyObject) o;
return Objects.equals(obj1, myObject.obj1) &&
Objects.equals(obj2, myObject.obj2);
}
}
以上两种方法都是常见的比较两个对象是否相等的方式。你可以根据自己的需求和偏好选择其中之一来实现。