You do not want to convert to String
because that would compare the numbers lexicographically rather than numerically.
I will take your question to mean, "How do I create a compareTo()
method for doubles?"
I also think you are using this to implement a data structure for doubles.
Here is how I would go about it.
When you construct a data structure, you will construct it as a Double
object.
Double
is a built-in class in java.lang
package that boxes the double
primitive.
Then, java will automatically cast them to that type.
The reason you want to use the Double
class as the defining type for your data structure is so that you can use its built-in compareTo
method. There is no way to make the primitive data type double
contain the compareTo
method.
Here is some code to help you get started for example:
TreeMap <Double, String> myDoubleMap = new TreeMap <Double, String> (10);
for (int i = 0; i < 10; i++)
myDoubleMap.put ( Math.sqrt( 10.0 * i) , "" + i);
System.out.println(myDoubleMap);
(Make sure you import java.util.TreeMap
if you are to run this example)