Question

Why equal method is false when I compare two double primitive types with the same value? However integer is not

public class EqualMethod {
    public static void main(String[] args) {        
        Double value1 = 6.2;
        Double value2 = 6.2;        
        System.out.println(value1 == value2);

        Integer number1 = 2;
        Integer number2 = 2;
        System.out.println(number1 == number2);  
    } 
}
Était-ce utile?

La solution

You are comparing references and not values. Either do:

value1.equals(value2);

or do:

value1.doubleValue() == value2.doubleValue();

Read more about Autoboxing here to figure out why this works sometimes (with integers) and why sometimes it does not. Notice that all integers are a summation of a power of 2: 6 = 2 + 4, whereas decimals are not: 6.2 = 4 + 2 + 1/8 + ...

Autres conseils

Both variables are initialized by a boxing conversion to a Double object. When using == on objects, the references are compared if they are the same object, and the contents are not compared.

To compare the contents, you can use either the equals method, or you can check if the result of calling compareTo is equal to 0. Or, you can declare both variables as double, and then == will compare the values directly.

== Meant for reference comparison

.equals Meant for content comparison

1.In your code two objects will be created with references value1 and value2 pointing to different object.If you use value1==value2 it will return false.If references points to same object it will return true

Double value1 = 6.2;
Double value2 = 6.2;   

2.If you use value1.equals(value2) it will compare the content of the objects which will return true

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top