Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

== or equals when comparing final static fields

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?

like image 636
StepTNT Avatar asked Sep 30 '22 06:09

StepTNT


1 Answers

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.

like image 175
Audrius Meškauskas Avatar answered Oct 05 '22 08:10

Audrius Meškauskas