Java Reference
In-Depth Information
The floatToIntBits() and doubleToIntBits() methods are used in im-
plementations of the equals() and hashCode() methods that must take float
and double fieldsintoaccount. floatToIntBits() and doubleToIntBits()
allow equals() and hashCode() to respond properly to the following situations:
equals() must return true when f1 and f2 contain Float.NaN (or d1
and d2 contain Double.NaN ). If equals() was implemented in a manner
similar to f1.floatValue() == f2.floatValue() (or
d1.doubleValue() == d2.doubleValue() ), this method would re-
turn false because NaN is not equal to anything, including itself.
equals() must return false when f1 contains +0.0 and f2 contains -0.0
(or vice-versa), or d1 contains +0.0 and d2 contains -0.0 (or vice-versa). If
equals() was implemented in a manner similar to f1.floatValue()
== f2.floatValue() (or d1.doubleValue() ==
d2.doubleValue() ), this method would return true because +0.0 ==
-0.0 returns true.
Theserequirementsareneededforhash-basedcollections(discussedin Chapter5 )to
workproperly. Listing4-5 showshowtheyimpact Float 'sand Double 's equals()
methods:
Listing 4-5. Demonstrating Float' s equals() method in a NaN context and Double 's
equals() method in a +/-0.0 context
class FloatDoubleDemo
{
public static void main(String[] args)
{
Float f1 = new Float(Float.NaN);
System.out.println(f1.floatValue());
Float f2 = new Float(Float.NaN);
System.out.println(f2.floatValue());
System.out.println(f1.equals(f2));
System.out.println(Float.NaN == Float.NaN);
System.out.println();
Double d1 = new Double(+0.0);
System.out.println(d1.doubleValue());
Double d2 = new Double(-0.0);
System.out.println(d2.doubleValue());
Search WWH ::




Custom Search