Some Notable things about Java equals

equals() is not symmetric with treatment of null. From spec x.equals(null) should return false for all x not null, but the other way round just throws NPE!

When comparing arrays for equality use 2 helper methods: Arrays.equals() & Arrays.deepEquals.

Gauva Objects.equal(a,b) can be used to check equality based on member variables. Some pit falls:

If member variables are arrays make sure to use “Arrays” as Objects.equal checks for null and delegate back to equals in the object. The default implementation for Array equals is identity check.

Make sure to check a & b or not null before delegating to Objects.equal() if you are “inlining” referring to member variables of a or b.

Prefer, to use instanceof instead of getClass() as instanceof will return true for subclasses as well which will not break the euals contract when new subclass is written to modify behavior but not state!

Finally, Don’t forget to override hashcode when you override equals!

 

http://www.angelikalanger.com/Conferences/Slides/JavaEquals-ACCU-2002.pdf

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s