In .NET System.Object defines a static method
bool Equals(object a, object b);
That is a useful alternative to a.Equals(b) in cases where a may be null. It also returns true if both a and b are null.
I can’t find an equivalent method in Java’s framework (my Java is a bit rusty these days.) The most succinct code I can muster is:
(a==null && b==null) || (a!=null && a.Equals(b))
Does such a method exist?
NOTE I don’t want to take a dependency on any external framework. I’m just curious if this simple method exists in the core Java class library.
Currently, this does not exist in the core library, but it is one of the improvements that is being added with Java 1.7.
In Java 1.7, you can use
Objects.equals(Object a, Object b). Until then, I recommend implementing it yourself if you do not want to add an external dependency.source