tags:

views:

151

answers:

4

Sometimes, I see this:


if (a.equals(b)) do(something);

However, if a is null, a NullPointerException is thrown. Assuming when a==null and b==null or if just a==b that I would want to do(something). What's the simplest way to do this check without getting an exception?

+8  A: 
if( a==b || (a!=null && a.equals(b)) )

(The a==b handles the case when both are null.)

McDowell
+1, this is pretty much what various .equals() utility methods do, too. For example: http://commons.apache.org/lang/api/org/apache/commons/lang/ObjectUtils.html#equals%28java.lang.Object,%20java.lang.Object%29
PSpeed
I think we have a winner.
User1
Since not all equals() methods contain the "if (o == this) return true" optimization, I think this formulation is the clear winner, and is what I used in Guava's Objects.equal() method.
Kevin Bourrillion
A: 

Your answer is in your question:

if ((a == null && b == null) || a.equals(b))...

brian
Nevermind. that doesn't work either.
brian
I'm glad I'm not the only one that finds this a bit tricky.
User1
I think it's even funnier that someone upvoted this answer after the author already said it didn't work.
User1
A: 

if you want to do something on identity only, then

if (a==b) do(something)

If on on equality, then

if ((a==null && b==null) || a.equals(b)) do(something)

abc
I think this would throw an exception if a=null and b=something.
User1
You're right...
abc
+5  A: 

Another way of writing it.

if (a == null ? b == null : a.equals(b))
Peter Lawrey
Reads pretty well!
fastcodejava
Much more readable than the accepted answer
Steve Kuo
@Steve - that is a matter of opinion.
Stephen C
@Stephen C ,and the opinion seems to win majority+1 more readable and seems good
Ravisha
The problem with this version is that it completely ignores the a == b case which could save a lot of calculation for some some objects.
PSpeed
Or it could be a premature optimisation as equals should have this and it might be inlined. ;)
Peter Lawrey