// These would throw NPE if city is null:
city.equals(otherCity);
// Old school workaround:
if (city != null && city.equals(otherCity))
// Clean, null-safe:
Objects.equals(city, otherCity); // returns true if both are null, false if only one is
It was always weird to me that equals takes a "preferred" object. Equals always feels like a "no special argument" type of method. I think the new type classes will actually make it far more sensible, but I'm not sure how they'll work with subtyping.
Unless OpenJDK has gone mental, they never will. equals is fundamentally about values, == is fundamentally about references, and null is a real reference but has no value. Hence, equals, in regards to null, is nonsensical. The idea that 2 null pointers are the same reference is fine. The idea that the value of reference A is equal to the value of reference B because both A and B are null is an incorrect conclusion.
If null has no value, then foo.equals(null) should raise an exception rather than returning true/false, since by this logic it makes no sense to perform the operation.
Likewise, Objects::equals should not allow null values at all.
That's a clash of concerns - equals is specced to never throw. And removing that now is an issue. But yes, that was a mistake too. It's not the only aspect of java that is a mistake, but fixing it in a backwards compatible way would be a cure that is worse than the disease so it isn't done.
Objects.equals is pointless if 'null should throw' is the mindset. Just call a.equals(b) instead of Objects.equals(a, b) then.
At best a sane equals can be written that does a.equals(b) if both are non-null and throws NPE if either (or both) are, but, 'make a utility method' is a shitty solution to these problems.
View all comments
Show parent comment
9
u/edurbs Feb 18 '26
thanks, documented ;)