Skip to content

Commit 1afd29a

Browse files
trnljyemin
authored andcommitted
Merge pull request #133 from foursquare/bsonequals
JAVA-905: BasicBSONObject.equals doesn't handle Number values correctly
1 parent d677083 commit 1afd29a

File tree

2 files changed

+36
-4
lines changed

2 files changed

+36
-4
lines changed

src/main/org/bson/BasicBSONObject.java

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -333,9 +333,16 @@ public boolean equals( Object o ){
333333
return false;
334334
}
335335
else if ( a instanceof Number && b instanceof Number ){
336-
if ( ((Number)a).doubleValue() !=
337-
((Number)b).doubleValue() )
336+
Number aNumber = (Number) a;
337+
Number bNumber = (Number) b;
338+
if (aNumber instanceof Double || bNumber instanceof Double
339+
|| aNumber instanceof Float || bNumber instanceof Float) {
340+
if (aNumber.doubleValue() != bNumber.doubleValue()) {
341+
return false;
342+
}
343+
} else if (aNumber.longValue() != bNumber.longValue()) {
338344
return false;
345+
}
339346
}
340347
else if ( a instanceof Pattern && b instanceof Pattern ){
341348
Pattern p1 = (Pattern) a;

src/test/org/bson/BSONTest.java

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,14 @@
1818

1919
package org.bson;
2020

21+
import static org.testng.Assert.assertNotEquals;
22+
2123
import java.io.ByteArrayInputStream;
2224
import java.io.IOException;
23-
import java.util.*;
24-
25+
import java.util.ArrayList;
26+
import java.util.Date;
27+
import java.util.List;
28+
import java.util.Vector;
2529
import org.bson.io.BasicOutputBuffer;
2630
import org.bson.io.OutputBuffer;
2731
import org.bson.types.CodeWScope;
@@ -259,6 +263,27 @@ public void testCustomDecoders()
259263
assertFalse( BSON.getDecodingHooks( Date.class ).contains( tf ) );
260264

261265
}
266+
267+
@Test
268+
public void testEquals() {
269+
assertNotEquals(new BasicBSONObject("a", 1111111111111111111L), new BasicBSONObject("a", 1111111111111111112L),
270+
"longs should not be equal");
271+
272+
assertNotEquals(new BasicBSONObject("a", 100.1D), new BasicBSONObject("a", 100.2D),
273+
"doubles should not be equal");
274+
275+
assertNotEquals(new BasicBSONObject("a", 100.1F), new BasicBSONObject("a", 100.2F),
276+
"floats should not be equal");
277+
278+
assertEquals(new BasicBSONObject("a", 100.1D), new BasicBSONObject("a", 100.1D),
279+
"doubles should be equal");
280+
281+
assertEquals(new BasicBSONObject("a", 100.1F), new BasicBSONObject("a", 100.1F),
282+
"floats should be equal");
283+
284+
assertEquals(new BasicBSONObject("a", 100), new BasicBSONObject("a", 100L),
285+
"int and long should be equal");
286+
}
262287

263288
private class TestDate {
264289
final int year;

0 commit comments

Comments
 (0)