eclipse-vertx / vert.x

Vert.x is a tool-kit for building reactive applications on the JVM
http://vertx.io
Other
14.26k stars 2.07k forks source link

JsonObject: The equals method fails when comparing integers with floats. #5185

Closed ProgMaq closed 5 months ago

ProgMaq commented 5 months ago

Version

4.5.7

Context

Due to a modification of the equals method made 5 years ago, given an integer (2) and a float (2.3), this condition will not be satisfied "if (n1.doubleValue() == n2.doubleValue())...", so it will advance to the next condition which will truncate the value "if (n1.longValue() == n2.longValue())...", returning an erratic "true".

In other libraries like GSON, this same case returns "false".

Do you have a reproducer?

  public static void main(String[] args) {
    final JsonObject f = new JsonObject("{\"number\": 2.3}");
    final JsonObject i = new JsonObject("{\"number\": 2}");
    System.out.println(f.equals(i)); // print true
  }

Extra


      // special case for numbers
      if (thisValue instanceof Number && otherValue instanceof Number && thisValue.getClass() != otherValue.getClass()) {
        Number n1 = (Number) thisValue;
        Number n2 = (Number) otherValue;
        // floating point values
        if (thisValue instanceof Float || thisValue instanceof Double || otherValue instanceof Float || otherValue instanceof Double) {
          // compare as floating point double
          if (n1.doubleValue() == n2.doubleValue()) {
            // same value check the next entry
            continue;
          }
        }
        if (thisValue instanceof Integer || thisValue instanceof Long || otherValue instanceof Integer || otherValue instanceof Long) {
          // compare as integer long
          if (n1.longValue() == n2.longValue()) {
            // same value check the next entry
            continue;
          }
        }
      }
tsegismont commented 5 months ago

Thanks for the report, we'll look into it