Home > Net >  Understanding equals-Implementation: type-check and THEN type-cast
Understanding equals-Implementation: type-check and THEN type-cast

Time:09-20

Why is the type of the object checked and afterwards a new object created via type-cast?

Can someone provide an example, why it is done in the shown way?

Please see my comments in the snippet.

 @Override
    public boolean equals(Object o) {
        if (o == this) {
            return true;
        }
 
        // After this check I know for sure that the object is an instance of Complex.
        if (!(o instanceof Complex)) {
            return false;
        }
        
        // Why is this cast necessary? I know (already) that is of type Complex. So I has all members Complex has.
        Complex c = (Complex) o;
       
        return Double.compare(re, c.re) == 0
                && Double.compare(im, c.im) == 0;
    }

CodePudding user response:

From Java 14 on you can make instanceof and cast together. For more information look here:

https://openjdk.org/jeps/305

From the spec this is the design:

if (obj instanceof String s) {
     // can use s here
} else {
     // can't use s here
}

CodePudding user response:

Because the Java compiler simply does not go that far in optimizing your code. I would assume it is possible to implement such an optimization (although it sounds easier said than done, it probably needs a good amount of work to make o count as Complex after the if check), but javac has been always built around as little optimizations as possible.

CodePudding user response:

People indeed found it unreasonable to need a explicit cast. And came up with the following "improvement." But this still is just syntactic suggar. From Object to Complex would need a cast. That at compile time this is clear, does not promote an Object variable to a Complex variable, as in some other languages.

In this case there is a weird usage:

    if (!(o instanceof Complex c)) {
        return false;
    }       
    // c known here, weird as it is.
    ...

One would only expect @Level_Up's solution.

  • Related