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 e开发者_如何学Goquivalent 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.
I think what you want is ObjectUtils.equals.
ObjectUtils.equals(null, null) = true
ObjectUtils.equals(null, "") = false
ObjectUtils.equals("", null) = false
ObjectUtils.equals("", "") = true
ObjectUtils.equals(Boolean.TRUE, null) = false
ObjectUtils.equals(Boolean.TRUE, "true") = false
ObjectUtils.equals(Boolean.TRUE, Boolean.TRUE) = true
ObjectUtils.equals(Boolean.TRUE, Boolean.FALSE) = false
If you are interested, here is the code from the library...
public static boolean equals(Object object1, Object object2) {
if (object1 == object2) {
return true;
}
if ((object1 == null) || (object2 == null)) {
return false;
}
return object1.equals(object2);
}
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
ObjectUtils in Apache Commons provides such a method.
精彩评论