Compare two objects with a check for null - comparison

Is there a method in the JDK that compares two objects for equality, accounting for nulls? Something like this:
public static boolean equals(Object o1, Object o2)
{
if (o1 == null)
{
return o2 == null; // Two nulls are considered equal
}
else if (o2 == null)
{
return false;
}
return o1.equals(o2);
}
It seems silly to write this method myself since I would think that it has to exist already somewhere.

Java 7.0 added a new handy class: Objects.
It has a method exactly for this: Objects.equals(Object a, Object b)

Apache Commons Lang has such a method: ObjectUtils.equals(object1, object2). You don't want generics on such a method, it will lead to bogus compilation errors, at least in general use. Equals knows very well (or should - it is part of the contract) to check the class of the object and return false, so it doesn't need any additional type safety.

FWIW, this was my implementation:
private static boolean equals(Object a, Object b) {
return a == b || (a != null && a.equals(b));
}
In my application, I know that a and b will always be the same type, but I suspect this works fine even if they aren't, provided that a.equals() is reasonably implemented.

public static boolean equals(Object object1, Object object2) {
if (object1 == null || object2 == null) {
return object1 == object2;
}
return object1.equals(object2);
}

If you are worried about NullPointerExceptions you could just test equality like:
if (obj1 != null && obj1.equals(obj2)) { ... }
The general contract of equals() is that a non-null object should never be equal to a null reference, and that the equals() method should return false if you are comparing an object to a null reference (and not throw a NPE).

Whenever I come across a need and think "this is so common Java must have it" but find it doesn't, I check the Jakarta Commons project. It almost always has it. A quick search of the commons-lang API (which has the most basic of common utilities) shows an equals() method that provides what you want.

Jakarta Commons Lang API has what you are looking for ObjectUtils.equals(Object,Object)

Related

Why can't I use rule of equality when overriding == operator?

void main() => Foo() == 1;
class Foo {
#override
bool operator ==(Object other) {
print(super == this); // true
// print(this == super); // Compile error
return super == other;
}
}
There are 2 questions.
Why can't I do this == super?
If you look at the return statement return super == other, you can tell the operator == is called on the Object class, so is the entire == implementation not a call which has been delegated to the Object class?
Let me explain the 2nd question further if it wasn't clear. Let's say I check for
Foo() == 1
The == operator defined in Foo class will be invoked and there all I'm doing is return super == other that means Object's == operator is being invoked and the other is int, so where the Foo instance in above code is? Here, it is only Object and int. I think super is doing something else too, not sure what is.
To answer your questions:
You can't do this == super because super is not an expression which is explained if you try run the program (the analyzed could give a better explanation):
bin/stackoverflow.dart:7:19: Error: Can't use 'super' as an expression.
To delegate a constructor to a super constructor, put the super call as an initializer.
print(this == super); // Compile error
^^^^^
Which also make sense since super is not an object. It is a concept we can use to specify if we want to refer to fields/methods that are overridden. But we cannot use super as some kind of object since our object is not multiple objects in layers where you can extract a layer and then represent this as another object. Instead, our object is a combined implementation based on how you define your class.
Yes, you're basically calling the Object's == operator when you return super == other.
Supplementary example:
But remember, we are just calling the == operator defined in Object. Our object is still a combined data structure which can be illustrated by this example:
class A {
final int a = 5;
int getA() => a;
}
class B extends A {
int get a => 10;
int getA() {
return super.getA();
}
}
void main() {
print(B().getA()); // 10
}
You can see that even if we call super.getA() we are still operating on a B object where we have overridden the a field but we are calling the A.getA() method.

What does the exclamation mark mean before a function call?

I was following a PR for Flutter and came across this code:
if (chunkCallback != null) {
chunkCallback!(0, 100);
}
What does the exclamation mark mean after chunkCallback? Nothing I search on Google works.
"!" is a new dart operator for conversion from a nullable to a non-nullable type.
Read here and here about sound null safety.
Use it only if you are absolutely sure that the value will never be null and do not confuse it with the conditional property access operator.
chunkCallback is a nullable reference to a function.
If you are sure that chunkCallback can't be null at runtime you can "Cast away nullability" by adding ! to it to make compiler happy
typedef WebOnlyImageCodecChunkCallback = void Function(
int cumulativeBytesLoaded, int expectedTotalBytes);
...
class Class1 {
final WebOnlyImageCodecChunkCallback? chunkCallback;
Class1(this.chunkCallback);
void test() {
if (chunkCallback == null) {
throw Exception("chunkCallback is null");
}
chunkCallback!.call(0, 100);
}
}
Esentially, ! in this case is a syntactic sugar for
(chunkCallback as WebOnlyImageCodecChunkCallback).call(0, 100);
I think it is a shorthand syntax for “Casting away nullability”, as per the docs: https://dart.dev/null-safety/understanding-null-safety#null-assertion-operator
The variable chunkCallback must be able to accept null and you cannot call a function on a nullable type without either using ! or ?. This is part of Darts sound null safety
Some great videos on this:
Flutter vid
YouTube vid
Even though the conditional statement checks for null, Dart still requires the exclamation mark before the function call. The difference between using ! over ? is that it will throw an exception instead of using the variable if the value is null.
Some examples:
class Car {
String? make; // String or null type
Car([this.make]); // parameter is optional
}
main() {
Car test = Car('Ford'); // initialised with a value
Car test2 = Car(); // no value given so null is default
// returns 4
if (test.make != null) {
print(test.make!.length); // ! still needed even though !=null condition stated
} else {
print('The value is null');
}
// returns The value is null
if (test2.make != null) {
print(test2.make!.length);
} else {
print('The value is null');
}
}
Above example shows that conditional check for null is not enough.
And choosing between ? and !
class Customer {
String? name;
String? surname;
Customer(this.name, [this.surname]); // constructor with optional parameter []
}
main() {
Customer ford = Customer('John'); //only name is given a value
// calling a method on a nullable type doesn't work
// so ? and ! used here after variable name and before method
print(ford.name!.length); // operation executed as usual => 4
print(ford.surname?.length); // ? on null value returns null => null
print(ford.surname!.length); // Exception is thrown => TypeError
}

Why does F# compiler check `this != null`? [duplicate]

What should IEquatable<T>.Equals(T obj) do when this == null and obj == null?
1) This code is generated by F# compiler when implementing IEquatable<T>. You can see that it returns true when both objects are null:
public sealed override bool Equals(T obj)
{
if (this == null)
{
return obj == null;
}
if (obj == null)
{
return false;
}
// Code when both this and obj are not null.
}
2) Similar code can be found in the question "in IEquatable implementation is reference check necessary" or in the question "Is there a complete IEquatable implementation reference?". This code returns false when both objects are null.
public sealed override bool Equals(T obj)
{
if (obj == null)
{
return false;
}
// Code when obj is not null.
}
3) The last option is to say that the behaviour of the method is not defined when this == null.
leppie is right. Just to elaborate on his answer (and confirm his suspicion that F# doesn't guarantee this != null): discriminated unions may be marked with the attribute [<CompilationRepresentation(CompilationRepresentationFlags.UseNullAsTrueValue)>] allowing cases to be represented by the value null. Option<'T> is such a type. The None case is represented by null at run-time. (None : option<int>).Equals(None) is syntactically valid. Here's a fun example:
[<CompilationRepresentation(CompilationRepresentationFlags.UseNullAsTrueValue)>]
type Maybe<'T> =
| Just of 'T
| Nothing
[<CompilationRepresentation(CompilationRepresentationFlags.Instance)>]
member this.ThisIsNull() = match this with Nothing -> true | _ -> false
Decompiling ThisIsNull with Reflector shows
public bool ThisIsNull()
{
return (this == null);
}
And the result:
Nothing.ThisIsNull() //true
The reason F# does this (I suspect) to optimize empty lists as null.
By adding this check, it allows one to call an instance method on a null instance without any problems.
See my blog post from a while back.
In C#, this is irrelevant.
To answer the question:
It should return true as both instances are null and deemed equal.
If this is null, the code can't be called, so that case needn't be considered (in C# anyway, there are cases where languages allow a null object to have a method dereferenced though obviously if it internally examines any of its non-existent fields it will error. Consider:
return x.Equals(y);
If x is null, we don't even get to call into Equals for the null check to count.
Hence we need only consider:
public bool Equals(T obj)
{
if(obj == null)
return false;
//logic defining equality here.
}
Where the possibility of both objects being null does come up, is when we are examining them from a static == operator override or from an IEqualityComparer<T> implementation:
public bool Equals(T x, T y)
{
if(x == null)
return y == null;
if(y == null)
return false;
//logic defining equality here.
}
Note that a useful shortcut here if equality can be lengthy to determine (e.g. comparing long strings), then we may take advantage of the fact that identity entails equality - that is something is always equal to itself, even Ayn Rand could figure that out ;) There are also algorithms that make comparing an item with itself quite common, making this shortcut well worth including. In this case the identity comparison already includes the check for both being null, so we leave it out again:
public bool Equals(T x, T y)
{
if(ReferenceEquals(x, y))
return true;
if(x == null || y == null)
return false;
//logic defining equality here.
}
For most methods I assume undefined behavior when called with this==null. That's because most programmers write their code under the assumption that this!=null, which is guaranteed by the C# specification if the calling code is written in C#.
That's why every sane caller of x.Equals(y) should either know for sure that that x is not null, or add a manual null check.
In most cases I wouldn't call Equals directly at all, but instead use EqualityComparer<T>.Default.
I would definitelly go with option 1:
if (this == null)
{
return obj == null;
}
if (obj == null)
{
return false;
}
null object always equals null object.
Sample code is in the MSDN: http://msdn.microsoft.com/en-us/library/ms131190.aspx?ppud=4
If this==null you will get a runtime exception calling Equals() on that object.

Spring Data Neo4j 4 and dynamic properties

At my Neo4j/SDN 4 project I have a following entity:
#NodeEntity
public class Value extends BaseEntity {
#Index(unique = false)
private Object value;
private String description;
...
}
During the application run-time I want to be able to add a new dynamic properties to Value node, like for example value_en_US, value_fr_FR.
Right now I don't know what exact properties will be added to a particular Value node during application run-time so I can't define these properties at the code as a separate fields in Value.
Is there at SDN 4 any mechanisms to define these properties during the application run-time? I need something similar to DynamicProperties from SDN 3.
There is no such functionality in SDN 4, but it will be added in SDN 5 through a #Properties annotation on Map.
It will be available for testing in snapshot version very soon.
Check out this commit for more details
You might also want to look at this response to a similar question.
https://stackoverflow.com/a/42632709/5249743
Just beware that in that answer the function:
public void addAllFields(Class<?> type) {
for (Field field : type.getDeclaredFields()) {
blacklist.add(field.getName());
}
if (type.getSuperclass() != null) {
addAllFields(type.getSuperclass());
}
}
is not bullet proof. For one thing it doesn't look at #Property annotations. So if you want to go down that route keep your eyes open.
An 'improvement' is
public void addAllFields(Class<?> type) {
for (Field field : type.getDeclaredFields()) {
blacklist.add(findName(field));
}
if (type.getSuperclass() != null) {
addAllFields(type.getSuperclass());
}
}
private String findName(Field field) {
Property property = field.getAnnotation(Property.class);
if(property == null || "".equals(property.name())) {
return field.getName();
} else {
return property.name();
}
}
But this obviously doesn't look for the annotation on methods...

Equals for domain class in grails

The following equals code returns wrong result for domain
boolean equals(o) {
if (o == null) return false
if (this.is(o)) return true
getClass() == o.class && id == o.id
}
For two loaded entities with same id return false. Id are equals (one record in DB). But classes not same.
The entities -- fields in another domains. And it looks like GORM used some wrapper classes.
How to avoid this kind of problem?
As you are seeing, requiring that the classes be the same is overly strict. Using instanceof is usually safer, e.g.
class Foo {
boolean equals(o) {
if (!o) return false
if (is(o)) return true
o instanceof Foo && id == o.id
}
}
Using id in equals or hashCode is generally a bad idea in domain classes since you can't compare persistent and non-persistent classes. For example
class Foo {
String name
boolean equals(o) {
if (!o) return false
if (is(o)) return true
o instanceof Foo && id == o.id
}
}
With this class, this would fail:
new Foo(name: 'foo').save()
assert Foo.findByName('foo') == new Foo(name: 'foo')
but all of the important class data (in this case just the name property) is identical in both cases.
Even worse, assuming you create a hashCode method that's similarly broken, if you add a non-persistent instance to a hash-based collection (e.g. HashSet) and then save it, its id will change from null to some long value and so will its hashcode value. This will cause the instance to become "lost" in the collection.
Where is special method in GormInstanceApi
/**
* Proxy aware instanceOf implementation.
*/
boolean instanceOf(D o, Class cls) {
if (o instanceof EntityProxy) {
o = (D)((EntityProxy)o).getTarget()
}
return o in cls
}
Using of this method solved problem

Resources