Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy doesn't java.lang.Number implement Comparable?
    primarykey
    data
    text
    <p>Does anyone know why <code>java.lang.Number</code> does not implement <code>Comparable</code>? This means that you cannot sort <code>Number</code>s with <code>Collections.sort</code> which seems to me a little strange.</p> <p><strong>Post discussion update:</strong></p> <p>Thanks for all the helpful responses. I ended up doing <a href="http://radioeiffel.blogspot.com/2009/02/what-java-can-sort-numbers.html" rel="noreferrer">some more research about this topic</a>.</p> <p>The simplest explanation for why java.lang.Number does not implement Comparable is rooted in mutability concerns.</p> <p>For a bit of review, <code>java.lang.Number</code> is the abstract super-type of <code>AtomicInteger</code>, <code>AtomicLong</code>, <code>BigDecimal</code>, <code>BigInteger</code>, <code>Byte</code>, <code>Double</code>, <code>Float</code>, <code>Integer</code>, <code>Long</code> and <code>Short</code>. On that list, <code>AtomicInteger</code> and <code>AtomicLong</code> to do not implement <code>Comparable</code>.</p> <p>Digging around, I discovered that it is not a good practice to implement <code>Comparable</code> on mutable types because the objects can change during or after comparison rendering the result of the comparison useless. Both <code>AtomicLong</code> and <code>AtomicInteger</code> are mutable. The API designers had the forethought to not have <code>Number</code> implement <code>Comparable</code> because it would have constrained implementation of future subtypes. Indeed, <code>AtomicLong</code> and <code>AtomicInteger</code> were added in Java 1.5 long after <code>java.lang.Number</code> was initially implemented.</p> <p>Apart from mutability, there are probably other considerations here too. A <code>compareTo</code> implementation in <code>Number</code> would have to promote all numeric values to <code>BigDecimal</code> because it is capable of accommodating all the <code>Number</code> sub-types. The implication of that promotion in terms of mathematics and performance is a bit unclear to me, but my intuition finds that solution kludgy.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

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