As you may know overriding the equals method could be very important when writing java classes, consider the following:
Always check the implemetation to be:
- Reflexive: For any
x != null
:x.equals(x)
must betrue
. - Symetric: For any
x,y != null
:x.equals(y)
must be equals toy.equals(x)
. - Transitive: For any
x,y,z != null
: ifx.equals(y)
istrue
andy.equals(z)
istrue
,x.equals(z)
must betrue
. - Consistent: For any
x,y != null
:x.equals(y)
must returns the same result across invocations unless, the state of ofx
ory
changes. - Implement hashcode: If you are overriding equals also override
hashCode()
Also would be good to check:
- Override
equals(Object obj)
: Using@Override
- Use
instanceof
inside the equals method.
A tool that simplify this is:
- Apache commons equals builder.
References:
- Bloch Joshua, 2008. Item 8 “Obey the general contract when overriding equals” Effective Java Second Edition,pp.33.
Use the following when comparing nested objects:
(member == cmpObj.member || (member !=null && member.equals(cmpObj.member)) )