views:

392

answers:

10

The contract of equals with regards to null, is as follows:

For any non-null reference value x, x.equals(null) should return false.

This is rather peculiar, because if o1 != null and o2 == null, then we have:

o1.equals(o2) // returns false
o2.equals(o1) // throws NullPointerException

The fact that o2.equals(o1) throws NullPointerException is a good thing, because it alerts us of programmer error. And yet, that error would not be catched if for various reasons we just switched it around to o1.equals(o2), which would just "silently fail" instead.

So the questions are:

  • Why is it a good idea that o1.equals(o2) should return false instead of throwing NullPointerException?
  • Would it be a bad idea if wherever possible we rewrite the contract so that anyObject.equals(null) always throw NullPointerException instead?

On comparison with Comparable

In contrast, this is what the Comparable contract says:

Note that null is not an instance of any class, and e.compareTo(null) should throw a NullPointerException even though e.equals(null) returns false.

If NullPointerException is appropriate for compareTo, why isn't it for equals?

Related questions


A purely semantical argument

These are the actual words in the Object.equals(Object obj) documentation:

Indicates whether some other object is "equal to" this one.

And what is an object?

JLS 4.3.1 Objects

An object is a class instance or an array.

The reference values (often just references) are pointers to these objects, and a special null reference, which refers to no object.

My argument from this angle is really simple.

  • equals tests whether some other object is "equal to" this
  • null reference gives no other object for the test
  • Therefore, equals(null) should throw NullPointerException
+7  A: 

An exception really should be an exceptional situation. A null pointer might not be a programmer error.

You quoted the existing contract. If you decide to go against convention, after all this time, when every Java developer expects equals to return false, you'll be doing something unexpected and unwelcome that will make your class a pariah.

I could't disagree more. I would not rewrite equals to throw an exception all the time. I'd replaced any class that did that if I were its client.

duffymo
+1 for "will make your class a pariah".
fastcodejava
+1  A: 

Personally, I'd rather it perform as it does.

The NullPointerException identifies that the problem is in the object against which the equals operation is being performed.

If the NullPointerException was used as you suggest and you tried the (sort of pointless) operation of...

o1.equals(o1) where o1= null... Is the NullPointerException thrown because your comparison function is screwed or because o1 is null but you didn't realise? An extreme example, I know, but with current behaviour I feel you can tell easily where the problem lies.

Rob L
+1  A: 

Not that this is neccessarily an answer to your question, it is just an example of when I find it useful that the behaviour is how it is now.

private static final String CONSTANT_STRING = "Some value";
String text = getText();  // Whatever getText() might be, possibly returning null.

As it stands I can do.

if (CONSTANT_STRING.equals(text)) {
    // do something.
}

And I have no chance of getting a NullPointerException. If it were changed as you suggested, I would be back to having to do:

if (text != null && text.equals(CONSTANT_STRING)) {
    // do something.
}

Is this a good enough reason for the behaviour to be as it is?? I don't know, but it is a useful side-effect.

DaveJohnston
A: 

This is a tricky question. For backward compatability you can't do so.

Imagine the following scenario

void m (Object o) {
 if (one.equals (o)) {}
 else if (two.equals (o)) {}
 else {}
}

Now with equals returning false else clause will get executed, but not when throwing an exception.

Also null is not really equal to say "2" so it makes perfect sense to return false. Then it is probably better to insist null.equals("b") to return also false :))

But this requirement does make a strange and non symmetric equals relation.

Anton
+1  A: 

I think it's about convenience and more importantly consistency - allowing nulls to be part of the comparison avoids having to do a null check and implement the semantics of that each time equals is called. null references are legal in many collection types, so it makes sense they can appear as the right side of the comparison.

Using instance methods for equality, comparison etc., necessarily makes the arrangement asymmetric - a little hassle for the huge gain of polymorphism. When I don't need polymorphism, I sometimes create a symmetric static method with two arguments, MyObject.equals(MyObjecta, MyObject b). This method then checks whether one or both arguments are null references. If I specifically want to exclude null references, then I create an additional method e.g. equalsStrict() or similar, that does a null check before delegating to the other method.

mdma
+1  A: 

Note that the contract is "for any non-null reference x". So the implementation will look like:

if (x != null) {
    if (x.equals(null)) {
        return false;
    }
}

x need not be null to be deemed equal to null because the following definition of equals is possible:

public boolean equals(Object obj) {
    // ...
    // If someMember is 0 this object is considered as equal to null.
    if (this.someMember == 0 and obj == null) {
         return true;
    }
    return false;
}
Vijay Mathew
+1  A: 

In the first case o1.equals(o2) returns false because o1 is not equal to o2, which is perfectly fine. In the second case, it throws NullPointerException because o2 is null. One cannot call any method on a null. It may be a limitation of programming languages in general, but we have to live with it.

It is also not a good idea to throw NullPointerException you are violating the contract for the equals method and making things more complex than it has to be.

fastcodejava
+1  A: 

There are many common situations where null is not in any way exceptional, e.g. it may simply represent the (non-exceptional) case where a key has no value, or otherwise stand for “nothing”. Hence, doing x.equals(y) with an unknown y is also quite common, and having to always check for null first would be just wasted effort.

As for why null.equals(y) is different, it is a programming error to call any method on a null reference in Java†, and therefore exceptional. However, I would argue that comparing an Object to null is not, and apparently this is the stance taken by the authors of Java.

And, from a pragmatic perspective it allows e.g. the implementation of equals in Object to be just return this == obj; without having to check for null. And since this is the way it is specified, it is a programming error to break the contract and raise an exception.

† In other languages the equivalent of null may be an object, e.g. in Ruby nil is of the class NilClass.

Arkku
+9  A: 

To the question of whether this asymmetry is inconsistent, I think not, and I refer you to this ancient Zen ko-an:

  • Ask any man if he's as good as the next man and each will say yes.
  • Ask any man if he's as good as nobody and each will say no.
  • Ask nobody if it's as good as any man and you'll never get a reply.

At that moment, the compiler reached enlightenment.

Sean Owen
I wonder if the designers of the Java programming language really thought of this or if they just didn't notice the asymmetry... ;-)
Jesper
+1  A: 

Think of how .equals is related to == and .compareTo is related to the comparison operators >, <, >=, <=.

If you're going to argue that using .equals to compare an object to null should throw a NPE, then you'd have to say that this code should throw one as well:

Object o1 = new Object();
Object o2 = null;
boolean b = (o1 == o2); // should throw NPE here!

The difference between o1.equals(o2) and o2.equals(o1) is that in the first case you're comparing something to null, similar to o1 == o2, while in the second case, the equals method is never actually executed so there's no comparison happening at all.

Regarding the .compareTo contract, comparing a non-null object with a null object is like trying do this:

int j = 0;
if(j > null) { 
   ... 
}

Obviously this won't compile. You can use auto-unboxing to make it compile, but you get a NPE when you do the comparison, which is consistent with the .compareTo contract:

Integer i = null;
int j = 0;
if(j > i) { // NPE
   ... 
}
Angus