简体   繁体   中英

compare -999 in type double in Java with == and .equals()

Edit : Some people stated that this is possible duplicate of one of question asking how to compare string values. I was asking about comparing double with int, that is why .equal() did not work.


First, I set a LinkedList of doubles with first element = -999

then if the comparison is

return listOfNumber.getFirst().equals(-999);

the outcome will be false.

However if the comparison is written as

return listOfNumber.getFirst()== -999;

Then the outcome will be true.

I thought .equals() compares the value and == compare the object and == can only take -128 to 127. So why exactly I cannot use .equals to compare doubles?

Also if the LinkedList is String with first element = "a" if I use

return ListOfString.getFirst() == "a";

then the outcome is false but if I use

return ListOfString.getFirst().equals("a");

then the outcome is true.

I am very confused why the comparison of double and string need to be different to yield correct result?

Your problem is caused by autoboxing in Java.

Assuming (as you stated listOfNumber is a list of Double`):

ArrayList<Double> listOfNumber = new ArrayList<>();
listOfNumber.add(-999);

Since Java knows the signature of ... add(T) is ... add(Double) , your add statement gets translated to:

listOfNumber.add(Double.valueOf(-999));

When you are executing

return listOfNumber.getFirst().equals(-999);

Java knows that Object.equals accepts a Object , and -999 fits an integer (the default type for a number), so it translates it to:

return listOfNumber.getFirst().equals(Integer.valueOf(-999));

Since a Integer and a Double aren't the same, it returns false, but for the == case, the java compilers gets smarter, and knows (double)-999 == (integer)-999

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM