Java Reference
In-Depth Information
Solution #2
Use the Float class compare() method to perform the comparison. The fol-
lowing example demonstrates the use of the Float.compare(float, float)
method.
System.out.println(Float.compare(float1, float3)); //
Result: -1
System.out.println(Float.compare(float2, float3)); //
Result: -1
System.out.println(Float.compare(float1, float1)); //
Result: 0
System.out.println(Float.compare(float3, float2)); //
Result: 1
How It Works
The most useful way to compare two float objects is to use the compareTo() meth-
od. This method will perform a numeric comparison against the given float objects.
The result will be an integer value indicating whether the first float is numerically
greater than, equal to, or less than the float that it is compared against. If a float value is
NaN , it is considered to be equal to other NaN values or greater than all other float val-
ues. Also, a float value of 0.0f is greater than a float value of -0.0f .
An alternative to using compareTo() is the compare() method, which is also
native to the Float class. The compare() method was introduced in Java 1.4, and it
is a static method that compares two float values in the same manner as com-
pareTo() . It only makes the code read a bit differently. The format for the com-
pare() method is as follows:
Float.compare(primitiveFloat1, primitiveFloat2)
The compare() method shown will actually make the following call using com-
pareTo() :
new Float(float1).compareTo(new Float(float2)
Search WWH ::




Custom Search