Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It's worth mentioning that the following expression:</p> <pre><code>new Long(10).equals(new Integer(10)) </code></pre> <p>is always <code>false</code>, which tends to trip everyone up at some point or another. So not only can you not compare arbitrary <code>Number</code>s but you can't even determine if they're equal or not.</p> <p>Also, with the real primitive types (<code>float</code>, <code>double</code>), determining if two values are equal is tricky and has to be done within an acceptable margin of error. Try code like:</p> <pre><code>double d1 = 1.0d; double d2 = 0.0d; for (int i=0; i&lt;10; i++) { d2 += 0.1d; } System.out.println(d2 - d1); </code></pre> <p>and you'll be left with some small difference.</p> <p>So back to the issue of making <code>Number</code> <code>Comparable</code>. How would you implement it? Using something like <code>doubleValue()</code> wouldn't do it reliably. Remember the <code>Number</code> subtypes are:</p> <ul> <li><code>Byte</code>;</li> <li><code>Short</code>;</li> <li><code>Integer</code>;</li> <li><code>Long</code>;</li> <li><code>AtomicInteger</code>;</li> <li><code>AtomicLong</code>;</li> <li><code>Float</code>;</li> <li><code>Double</code>;</li> <li><code>BigInteger</code>; and</li> <li><code>BigDecimal</code>.</li> </ul> <p>Could you code a reliable <code>compareTo()</code> method that doesn't devolve into a series of if instanceof statements? <code>Number</code> instances only have six methods available to them:</p> <ul> <li><code>byteValue()</code>;</li> <li><code>shortValue()</code>;</li> <li><code>intValue()</code>;</li> <li><code>longValue()</code>;</li> <li><code>floatValue()</code>; and</li> <li><code>doubleValue()</code>.</li> </ul> <p>So I guess Sun made the (reasonable) decision that <code>Number</code>s were only <code>Comparable</code> to instances of themselves.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload