1

In Java, the Integer class implements Comparable<Integer>, Double implements Comparable<Double>, and so on. This means you can write code like

new Integer(0).compareTo(new Integer(1))

However, you can not compare different types:

new Integer(0).compareTo(new Double(1)) // illegal!

Why don't the various Number subclasses implement Comparable to each other?

Note that you can compare an integer and a double through 0 < 1.1 using primitives.

Ypnypn
  • 933
  • 1
  • 8
  • 21
  • How can you compare an `Integer` with a `Double`? – Luiggi Mendoza May 12 '14 at 21:30
  • What would a comparison between an integer and a double look like? How precise is this supposed to be? Mandatory reading around the subject: http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm – Jeroen Vannevel May 12 '14 at 21:31
  • Because all are of different type of objects. They doesn't come in same hierarchy. – Braj May 12 '14 at 21:31
  • 3
    This question adequately answeres this: http://stackoverflow.com/questions/480632/why-doesnt-java-lang-number-implement-comparable?rq=1 – Alcanzar May 12 '14 at 21:32
  • You can simply use the operators and rely on autounboxing. – gparyani May 12 '14 at 21:34
  • Comparable doesn't imply any type conversion. You can write your own Comparator which does type conversion. – Peter Lawrey May 12 '14 at 21:56
  • "Note that you can compare an integer and a double through 0 < 1.1 using primitives". Technically, this is not true. You are not comparing an integer and a double; the language dictates that the `int` automatically gets cast to `double`, so you are performing a type conversion and then comparing two `double`s. This occurs only in a few specific situations. C++ provides ways where you can get the compiler to auto-convert types to your heart's delight, which is great until you or someone else has to debug your code. – ajb May 12 '14 at 21:57

0 Answers0