Can anyone explain this interesting code: Double x = Double.NaN; Double y = Double.NaN; if (x.equals(y)) System.out.println("Wow, they are equal..."); I would have thought that they would not be equal since Double.NaN != Double.NaN. Thanks much. Bert
Open Group Certified Distinguished IT Architect. Open Group Certified Master IT Architect. Sun Certified Architect (SCEA).
Joined: Sep 29, 2000
Actually the FAQ addresses the == behavior of NaN but not the .equals behavior.
"JavaRanch, where the deer and the Certified play" - David O'Meara
Joined: Mar 17, 2000
In cases like this, the first place to go to is the API documentation. Atleast you will know if something you observe is the expected behaviour. Here's what I got from Java API documentation
public boolean equals(Object obj) Compares this object against the specified object. The result is true if and only if the argument is not null and is a Double object that represents a double that has the identical bit pattern to the bit pattern of the double represented by this object. For this purpose, two double values are considered to be the same if and only if the method doubleToLongBits(double) returns the same long value when applied to each. Note that in most cases, for two instances of class Double, d1 and d2, the value of d1.equals(d2) is true if and only if d1.doubleValue() == d2.doubleValue()
also has the value true. However, there are two exceptions: If d1 and d2 both represent Double.NaN, then the equals method returns true, even though Double.NaN==Double.NaN has the value false. If d1 represents .0 while d2 represents -0.0, or vice versa, the equal test has the value false, even though .0==-0.0 has the value true. This allows hashtables to operate properly. Overrides: equals in class Object Parameters: obj - the object to compare with. Returns: true if the objects are the same; false otherwise.
Hope that helps! Ajith
Joined: Nov 17, 2000
I tried to Compile the following Double x= Double.NaN; This doesn't work as Double.NaN can be assigned to only Vairables of primitive type (double).I would also like to point out the the equals() method takes objects as aruguments, it does not allow primitive types to be passed as arguments. Now the follwoing will surely print "True" Double x= new Double(Double.NaN); Double y= new Double(Double.NaN); if (x.equals(y)) System.out.println("True"); Hope this makes Sense. Correct me if I am wrong.
Joined: Nov 16, 2000
Sorry about that. That is the code I had in my test program. I just typed it in a hurry. Thanks for the clarification.