I have a java class which is something like this:
class MyClass {
MyClass(Object obj) {
m_Obj = obj
}
private Object m_Obj;
}
Because m_Obj could be null, my equals method has to look like this:
@Override
public boolean equals(
Object obj) {
if (!(obj instanceof MyObject))
return false;
MyObject other = (MyObject)obj;
if ((m_Obj == null) &&
(other.m_Obj == null)
return true;
if ((m_Obj == null) &&
(other.m_Obj != null)
return false;
if ((m_Obj != null) &&
(other.m_Obj == null)
return false;
return m_Obj.equals(other.m_Obj);
}
When I have multiple members of the class which may or may not be null, the equals function just becomes a long slog. I could write my own function:
public boolean equals(
Object a,
Object b) {
if ((a == null) &&
(b == null)
return true;
if ((a == null) &&
(b != null)
return false;
if ((a != null) &&
(b == null)
return false;
return a.equals(b);
}
I'm wondering if someone has already done this in one of the java/apache libraries?
Objects.equals
.