Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
675 views
in Technique[技术] by (71.8m points)

java - In which case could "a != a" return "true"?

java.lang.Math#min(double, double):

public static double min(double a, double b) {
    if (a != a) return a; // a is NaN
    if (a == 0.0d && b == 0.0d && Double.doubleToLongBits(b) == negativeZeroDoubleBits) return b;
    return (a <= b) ? a : b;
}

In which case could a != a return true? It seems that it's when a is NaN, but I can't imagine an example. Could you please provide one?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A simple example is

double d = Double.NaN; // or
double d = 0.0/0.0; // or
double d = Double.POSITIVE_INFINITY + Double.NEGATIVE_INFINITY;
if (Double.isNaN(a)) { // tests if a != a
   // do something

BTW Double.compare() does see NaN as equal

if (Double.compare(d, d) == 0) // always.

With multiple threads this is possible for any type and value. e.g.

if (a != /* another thread changes 'a' */ a) {
    // a thread changed a while you were looking at it.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...