Comparing Object with null

From: Asad Khan (uoft_cstutor_at_yahoo.com)
Date: 10/31/03


Date: Fri, 31 Oct 2003 16:21:14 GMT


  public boolean equals(Object o) {
    if (!(o.equals(null))) { // *
      if (o instanceof foo) {
        if (this.equals(o)) {
          return true;
        }
      }
    }
    return false;
  }

I have the above method in a class foo. When I run the following code:

f.equals(f)

where f is an object of class foo, then I get a nullpointerexception in this
method. The reason is that since f is of type foo, in line * it recursively
calls the equals method and then o becomes null, and of course I can't
dereference null.

So how can I check if an object is null or not?

Thanks.



Relevant Pages

  • Re: Comparing Object with null
    ... > public boolean equals{ ... > I have the above method in a class foo. ... // Your attempted implementation of equals ... public boolean equals(Object obj) ...
    (comp.lang.java.programmer)
  • comparing Object with null
    ... public boolean equals{ ... I have the above method in a class foo. ... calls the equals method and then o becomes null, ... dereference null. ...
    (comp.lang.java)
  • Re: Comparing Object with null
    ... > public boolean equals{ ... > I have the above method in a class foo. ... > dereference null. ... Adam ...
    (comp.lang.java.programmer)
  • Re: Comparing Object with null
    ... "Asad Khan" wrote in message ... > public boolean equals{ ... > I have the above method in a class foo. ... If you want to see if the reference variable does ...
    (comp.lang.java.programmer)
  • Re: comparing Object with null
    ... >I have the above method in a class foo. ... The reason is that since f is of type foo, ... >calls the equals method and then o becomes null, ... >dereference null. ...
    (comp.lang.java)