Skip to content

Commit 761f694

Browse files
committed
JAVA-612: Properly define equals and hashCode for DBRefBase
1 parent 999fc10 commit 761f694

File tree

2 files changed

+35
-17
lines changed

2 files changed

+35
-17
lines changed

src/main/com/mongodb/DBRefBase.java

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -85,16 +85,23 @@ public DB getDB() {
8585
}
8686

8787
@Override
88-
public boolean equals(Object obj) {
89-
if (obj == this)
90-
return true;
91-
92-
if (obj instanceof DBRefBase) {
93-
DBRefBase ref = (DBRefBase) obj;
94-
if (_ns.equals(ref.getRef()) && _id.equals(ref.getId()))
95-
return true;
96-
}
97-
return false;
88+
public boolean equals(final Object o) {
89+
if (this == o) return true;
90+
if (o == null || getClass() != o.getClass()) return false;
91+
92+
final DBRefBase dbRefBase = (DBRefBase) o;
93+
94+
if (_id != null ? !_id.equals(dbRefBase._id) : dbRefBase._id != null) return false;
95+
if (_ns != null ? !_ns.equals(dbRefBase._ns) : dbRefBase._ns != null) return false;
96+
97+
return true;
98+
}
99+
100+
@Override
101+
public int hashCode() {
102+
int result = _id != null ? _id.hashCode() : 0;
103+
result = 31 * result + (_ns != null ? _ns.hashCode() : 0);
104+
return result;
98105
}
99106

100107
final Object _id;

src/test/com/mongodb/DBRefTest.java

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,14 +16,15 @@
1616

1717
package com.mongodb;
1818

19-
import java.net.*;
20-
import java.util.*;
19+
import com.mongodb.util.TestCase;
20+
import org.bson.BSONDecoder;
21+
import org.bson.BasicBSONDecoder;
22+
import org.bson.types.ObjectId;
23+
import org.testng.annotations.Test;
2124

22-
import org.bson.*;
23-
import org.bson.types.*;
24-
import org.testng.annotations.*;
25-
26-
import com.mongodb.util.*;
25+
import java.net.UnknownHostException;
26+
import java.util.ArrayList;
27+
import java.util.List;
2728

2829
public class DBRefTest extends TestCase {
2930

@@ -38,6 +39,16 @@ public DBRefTest() {
3839
}
3940
}
4041

42+
@Test(groups = {"basic"})
43+
public void testEqualsAndHashCode() {
44+
DBRef ref = new DBRef(_db, "foo.bar", 4);
45+
DBRef other = new DBRef(_db, "foo.bar", 4);
46+
assertEquals(ref, ref);
47+
assertEquals(ref, other);
48+
assertNotEquals(ref, new DBRefBase(_db, "foo.bar", 4));
49+
assertEquals(ref.hashCode(), other.hashCode());
50+
}
51+
4152
@Test(groups = {"basic"})
4253
public void testDBRefBaseToString(){
4354

0 commit comments

Comments
 (0)