10

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?

5
  • Handling null as a special case? It seems such a trivial solution that I assume there's a reason you can't do that? Please elaborate. Commented Jan 29, 2010 at 23:40
  • This seems so trivial doesn't it? It appears to have stumped two others. This would make an interesting interview question. It's not that's hard, but that it's hard to do in a simple way.
    – User1
    Commented Jan 29, 2010 at 23:56
  • Sometimes the things that look simple are not always the easiest to accomplish. This was the first lesson I learned in calculus, and looking for the catch in anything has saved me from ALOT of missteps
    – Jason
    Commented Jan 30, 2010 at 1:34
  • Please clarify whether you want to compare the object or if the two a and b are pointing to same object? for first option the answers just if(a==b) for second option its if(a==b && a==null||a.equals(b) )
    – Ravisha
    Commented Jan 30, 2010 at 3:24
  • Just as equals() always works, compare the object.
    – User1
    Commented Jan 31, 2010 at 0:32

2 Answers 2

24

Another way of writing it.

if (a == null ? b == null : a.equals(b))
4
  • @Steve - that is a matter of opinion.
    – Stephen C
    Commented Jan 30, 2010 at 2:44
  • 1
    @Stephen C ,and the opinion seems to win majority +1 more readable and seems good
    – Ravisha
    Commented Jan 30, 2010 at 3:25
  • 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
    Commented Feb 1, 2010 at 17:52
  • 1
    Or it could be a premature optimisation as equals should have this and it might be inlined. ;) Commented Feb 2, 2010 at 21:00
22
if( a==b || (a!=null && a.equals(b)) )

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


Also be aware of the Java 7 and above Object.equals method:

if(java.util.Object.equals(a, b))
3
  • 4
    +1, this is pretty much what various .equals() utility methods do, too. For example: commons.apache.org/lang/api/org/apache/commons/lang/…
    – PSpeed
    Commented Jan 29, 2010 at 23:49
  • 1
    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. Commented Feb 2, 2010 at 23:45
  • Very good answer. Just one note: in your answer, Object should be Objects Commented Aug 11, 2017 at 13:39

Not the answer you're looking for? Browse other questions tagged or ask your own question.