Skip to content

Quirk: BigDecimal equals vs compareTo - #105

Open
mperor wants to merge 1 commit into
masterfrom
DAILY/92-bigdecimal-equals-vs-compareto
Open

mperor wants to merge 1 commit into
masterfrom
DAILY/92-bigdecimal-equals-vs-compareto

Conversation

@mperor

@mperor mperor commented Oct 28, 2026 •

Copy link
Copy Markdown
Owner

What you'll learn

  • BigDecimal.equals() compares both unscaled value and scale, so "2.0" and "2.00" are not equal
  • BigDecimal.compareTo() only compares numeric value, so it treats them as equal
  • this mismatch means HashSet (uses equals/hashCode) keeps both, while TreeSet (uses compareTo) keeps only one
  • new BigDecimal(double) exposes the exact binary floating-point value, while BigDecimal.valueOf(double) goes through Double.toString for the expected decimal; stripTrailingZeros() normalizes scale so equals agrees with compareTo

Why it matters

Mixing equals/hashCode with compareTo-based collections is a classic source of subtle bugs — deduplication that silently "half-works" depending on which Set implementation you pick, or BigDecimal constants that look equal but aren't.

Read more

BigDecimal#equals Javadoc

Quiz

Given Set<BigDecimal> set = new TreeSet<>(); set.add(new BigDecimal("2.0")); set.add(new BigDecimal("2.00"));, what is set.size()?

Answer 1 — `TreeSet` orders and deduplicates using `compareTo`, which ignores scale, so the second `add` is treated as a duplicate and discarded. A `HashSet` in the same scenario would keep both (size 2), since it uses `equals`/`hashCode`, which do consider scale.

Note on local verification: this environment only had JDK 21 installed, and the Gradle build requires JDK 25 via toolchain; JDK 25 auto-provisioning was blocked by network policy here, so I couldn't run ./gradlew locally. I compiled and ran the test manually against JDK 21 beforehand to check the logic, and CI (JDK 25) has now confirmed all tests pass.

Closes #92

@mperor mperor added the daily Queued for the daily learning PR label Oct 28, 2026
@github-actions

Copy link
Copy Markdown

Test Results

286 tests  +4   283 ✅ +4   6s ⏱️ ±0s
 81 suites +1     3 💤 ±0 
 81 files   +1     0 ❌ ±0 

Results for commit 84a674a. ± Comparison against base commit b42879b.

This pull request skips 1 and un-skips 1 tests.
pl.mperor.lab.java.design.pattern.creational.singleton.SingletonTest ‑ testSerializationSafe()
pl.mperor.lab.java.design.pattern.creational.singleton.SingletonTest ‑ testThreadSafe()

@mperor
mperor marked this pull request as ready for review October 28, 2026 07:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

daily Queued for the daily learning PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Quirk: BigDecimal equals vs compareTo

2 participants