Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix the equals method of JsonPrimitive to work with BigInteger #2311

Merged
merged 2 commits into from
Feb 6, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion gson/src/main/java/com/google/gson/JsonPrimitive.java
Original file line number Diff line number Diff line change
Expand Up @@ -282,7 +282,7 @@ public boolean equals(Object obj) {
return other.value == null;
}
if (isIntegral(this) && isIntegral(other)) {
return getAsNumber().longValue() == other.getAsNumber().longValue();
return new BigInteger(getAsNumber().toString()).equals(new BigInteger(other.getAsNumber().toString()));
MaicolAntali marked this conversation as resolved.
Show resolved Hide resolved
}
if (value instanceof Number && other.value instanceof Number) {
double a = getAsNumber().doubleValue();
Expand Down
6 changes: 2 additions & 4 deletions gson/src/test/java/com/google/gson/JsonPrimitiveTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -300,10 +300,8 @@ public void testEqualsAcrossTypes() {
@Test
public void testEqualsIntegerAndBigInteger() {
JsonPrimitive a = new JsonPrimitive(5L);
JsonPrimitive b = new JsonPrimitive(new BigInteger("18446744073709551621")); // 2^64 + 5
// Ideally, the following assertion should have failed but the price is too much to pay
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FWIW I vigorously disagree with this assessment. Saying values are equal when they aren't is pretty bad, and the fix is neither difficult nor expensive.

// assertFalse(a + " equals " + b, a.equals(b));
assertWithMessage("%s equals %s", a, b).that(a.equals(b)).isTrue();
JsonPrimitive b = new JsonPrimitive(new BigInteger("18446744073709551621"));
assertWithMessage("%s not equals %s", a, b).that(a.equals(b)).isFalse();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This may become irrelevant if we start using EqualsTester, but for now could you also check that b.equals(a) is false?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We could leave it until we implement EqualsTester

}

@Test
Expand Down