Check out the following code:
@Override
public int compareTo(final Intersection o) {
if (o == null)
return 0;
double distance = t;
double distance2 = o.t;
if (distance == distance2)
return 0;
return distance2 > distance ? -1 : 1;
}
All seems well however the fact that 0 may be returned on two different conditional occasions does somewhat bother me. If I do however move the variable assignments of distance
and distance2
to the top, my IDE warns me that
if (o == null)
return 0;
Would then be 'dead' code. If that's the case, should null even be checked in this scenario?
What I mean is:
@Override
public int compareTo(final Intersection o) {
double distance = t;
double distance2 = o.t;
if (o == null)
return 0;
if (distance == distance2)
return 0;
return distance2 > distance ? -1 : 1;
}
Final may be null, it just means it cannot be assigned and is visible in anonymous inner classes etc.
In your case, the problem is different: (see comments)
public int compareTo(final Intersection o) {
double distance = t;
double distance2 = o.t; // here you use it, potentially causing NPE
if (o == null) // if o was null, this is never reached
return 0;
if (distance == distance2)
return 0;
return distance2 > distance ? -1 : 1;
}
Your ide warns you because a final object can be null and you can get a null pointer exception on
double distance2 = o.t;
Hence the return statement or any statement inside the if o == null
will never reach/execute
if (o == null)
return 0;
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