Link to home
Start Free TrialLog in
Avatar of c0upal
c0upal

asked on

comparing two objects that have null values

is there away to use the .equals(function) when the calling object has a possibility that it would be null?

i.e.  if(a..equals(b))  //what if a = null;

as you know this will produce a NullPointerException.. but can is there another way to go around this?

ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Or if you want to consider two nulls as equal then:

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

Avatar of jaquo
jaquo

Yeah, basically just test if the value that could possibly be null actually IS null before trying a compare.  Then you could add an else statement to handle it from there.

If (a != null) {
  if (a.equals(b))
    //what it is you want to do
}
else {
  //what to do it a is null
}


Another simple solution can be helpful if you are sure that b is always not null, then have the statement like this,

if(b.equals(a)) {

}
In this case, even if a is null, u will not get nullpointer exception
> u will not get nullpointer exception

Not necessarily.
That depends on the implementation of the equals() method of b's class.
c0upal:
This old question needs to be finalized -- accept an answer, split points, or get a refund.  For information on your options, please click here-> http:/help/closing.jsp#1 
EXPERTS:
Post your closing recommendations!  No comment means you don't care.