I've returned back to Java after a little break with C# and I'm already tired of writing stuff like a.equals(b)
so I was wondering if is there a way to use the ==
operator without breaking my program.
Here's my situation:
public static class A {
public final static A STATIC_FIELD = new A(prop1, prop2);
public A method(int param){
return (param > 0.5) ? STATIC_FIELD : new A(prop1, prop2);
}
}
Now, can I replace equals
with ==
in the following snippet since I'm referring to the same object or is it wrong?
....
private bool method(){
A aInstance = getAInstance();
int param = Math.Random();
return aInstance.method(param).equals(A.STATIC_FIELD);
}
....
And what if the STATIC_FIELD
in a value taken from an enum
?
This depends on what do you want to do.
If you need to check if this is exactly the same object, use the direct comparison. If you need to check if the object wraps the same content (like string or number), then .equals should be used.
Most common errors with these methods seem coming from string comparison, where .equals returns true if the strings have the same content but == only returns true if this is the same instance of string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With