mirror of
https://gitflic.ru/project/openide/openide.git
synced 2026-08-26 15:27:45 +07:00
GitOrigin-RevId: 8b2b63fc6db476ca0c2cfe5cadd84db6c4236d0f
49 lines
1.8 KiB
HTML
49 lines
1.8 KiB
HTML
<html>
|
|
<body>
|
|
Reports subtraction in
|
|
<code>compareTo()</code> methods and methods implementing <code>java.util.Comparator.compare()</code>.
|
|
<p>
|
|
While it is a common idiom to
|
|
use the results of integer subtraction as the result of a <code>compareTo()</code>
|
|
method, this construct may cause subtle and difficult bugs in cases of integer overflow.
|
|
Comparing the integer values directly and returning <code>-1</code>, <code>0</code>, or <code>1</code> is a better practice in most cases.
|
|
</p>
|
|
<p>
|
|
Subtraction on floating point values that is immediately cast to integral type is also reported because precision loss is possible due to
|
|
rounding.
|
|
</p>
|
|
<p>
|
|
The inspection doesn't report when it's statically determined that value ranges are limited, and overflow never occurs.
|
|
Additionally, subtraction on <code>int</code> numbers greater than or equal to <code>0</code> will never overflow.
|
|
Therefore, this inspection tries not to warn in those cases.
|
|
</p>
|
|
<p>
|
|
Methods that always return zero or greater can be marked with the
|
|
<code>javax.annotation.Nonnegative</code> annotation or specified in this inspection's options.
|
|
</p>
|
|
<p><b>Example:</b></p>
|
|
<pre><code>
|
|
class DoubleHolder implements Comparable<DoubleHolder> {
|
|
double d;
|
|
public int compareTo(DoubleHolder that) {
|
|
return (int)(this.d - that.d);
|
|
}
|
|
}
|
|
</code></pre>
|
|
<p>A no-warning example because <code>String.length()</code> is known to be non-negative:</p>
|
|
<pre><code>
|
|
class A implements Comparable<A> {
|
|
final String s = "";
|
|
public int compareTo(A a) {
|
|
return s.length() - a.s.length();
|
|
}
|
|
}
|
|
</code></pre>
|
|
<!-- tooltip end -->
|
|
<p>
|
|
Use the options to list methods that are safe to use inside a subtraction.
|
|
Methods are safe when they return an <code>int</code> value that is always greater than or equal to <code>0</code>.
|
|
</p>
|
|
|
|
</body>
|
|
</html> |