Question

I am comparing two Doubles:

37.4238777160645

and

37.4238777160645

But Java does not consider them to be equal. I am comparing them in the following manner

if(object1.getLatitude()!=object2.getLatitude()){
    fail("objects are not equal "+object1.getLatitude()+":"+object2.getLatitude());
}

resulting in the following fail:

junit.framework.AssertionFailedError: objects are not equal  37.4238777160645:37.4238777160645

I don't understand why - Please advise.

Était-ce utile?

La solution 3

You should use java.lang.Double.compare() :

Double.compare(object1.getLatitude(), object2.getLatitude())

so you wil have :

if(Double.compare(object1.getLatitude(), object2.getLatitude()) != 0){
   fail("objects are not equal "+object1.getLatitude()+":"+object2.getLatitude());
}

Autres conseils

The issue has already been pointed out. But if you are using junit, it would be simpler to use the appropriate method:

assertEquals(object1.getLatitude(), object2.getLatitude());

or

assertEquals(object1.getLatitude(), object2.getLatitude(), 0.001d);

instead of using fail. That would also solve your issue.

Objects should be compared with .equals and not ==. By == you're comparing the references, which are not the same since you return a different object each time.

Use Double#equals to compare the values.

When applied to objects, the == operator returns true only when both operands are the same object.

Your method returns Double objects, so each call will produce a new object, and comparing them using == will always be false.

Use .equals(), which compares values of the Doubles:

if (!object1.getLatitude().equals(object2.getLatitude()))

Alternatively, change you methods to return double instead of Double, and your current code will work.

Floating point comparison in may programming languages should always take the form of

if(a-b op c)

where a and b are the numbers being compared and c being the threshold and op is either > or

<

.

This is because floating point representation in binary to not map directly to what is printed.

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