r/java • u/edurbs • Feb 17 '26
Objects.requireNonNullElse
I must have been living in a cave. I just discovered that this exists.
I can code
City city = Objects.requireNonNullElse(form.getCity(), defaultCity);
... instead of:
City city = form.getCity();
if(city == null){
city = defaultCity;
}
115
Upvotes
View all comments
Show parent comment
1
u/rzwitserloot Feb 21 '26
Unless OpenJDK has gone mental, they never will.
equalsis fundamentally about values,==is fundamentally about references, andnullis a real reference but has no value. Hence,equals, in regards tonull, 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 arenullis an incorrect conclusion.