[JAVA-1078] Implement equality for java.util.Pattern Created: 15/Jan/14  Updated: 23/Jan/14  Resolved: 21/Jan/14

Status: Closed
Project: Java Driver
Component/s: None
Affects Version/s: None
Fix Version/s: None

Type: Improvement Priority: Major - P3
Reporter: Stephen Lee Assignee: Unassigned
Resolution: Done Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Issue Links:
Related
related to JAVA-1090 For embedded $regex, BasicBSONObject ... Closed

 Description   

BSON that contains a document like

{"field":{"$regex":"^mypattern"}}

will be translated into a BSONObject object where the value of the field will be an instance of java.util.Pattern, which doesn't implement .equals(). Hence, two logically equivalent BSONObject objects will not considered equal.



 Comments   
Comment by Jeffrey Yemin [ 21/Jan/14 ]

Closing this, but feel free to open an issue about hashCode.

Comment by Jeffrey Yemin [ 21/Jan/14 ]

If you add

        System.out.println(a.equals(b));
        System.out.println(b.equals(a));

you'll see that equals is working as expected. The problem is that BasicBSONObject does not implement hashCode, so its hashCode method is not consistent with equals. So the driver is violating the contract:

     * Note that it is generally necessary to override the {@code hashCode}
     * method whenever this method is overridden, so as to maintain the
     * general contract for the {@code hashCode} method, which states
     * that equal objects must have equal hash codes.

Comment by Stephen Lee [ 21/Jan/14 ]

    BasicBSONObject a = new BasicBSONObject("firstName", Pattern.compile("^abc"));
    BasicBSONObject b = new BasicBSONObject("firstName", Pattern.compile("^abc"));
    Set<BSONObject> cache = new HashSet<>();
    cache.add(a);
    System.out.println("regex: " + cache.add(b));  // prints true, which suggests a != b
 
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
 
    a = new BasicBSONObject("ts", sdf.parse("2014-01-03T13:16:03.359Z"));
    b = new BasicBSONObject("ts", sdf.parse("2014-01-03T13:16:03.359Z"));
    cache = new HashSet<>();
    cache.add(a);
    System.out.println("dates: " + cache.add(b));  // prints false, which suggests a == b

Comment by Jeffrey Yemin [ 21/Jan/14 ]

Can you provide a test for this? Looking at https://github.com/mongodb/mongo-java-driver/blob/master/src/main/org/bson/BasicBSONObject.java#L349-349 it looks like Pattern equality is implemented.

Generated at Thu Feb 08 08:53:45 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.