From 7db19d307970b73559239ec343c92c7876510c2a Mon Sep 17 00:00:00 2001 From: Adrien Hopkins Date: Fri, 30 May 2025 20:10:09 -0500 Subject: Ensure LinearUnit&Prefix ==/hash obey contracts MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Previously, these classes' equals() and hashCode() methods did not obey the contracts: For equals(), I considered two values equal even if there was a very small deviation, in order to avoid floating-point error. This equals relation is not transitive (i.e. it is possible that a = b && b = c but a ≠ c), violating the contract of equals. This also makes it impossible to properly implement hashCode, as if two values are equal, they must have the same hash code. The solution I had provided is an ineffective hack, which could mess with hash maps and sets. I have changed the implementation to demand exact equality. I have also provided equalsApproximately() methods to both classes that use the old behaviour. Hash codes are only really used for hash maps, and the old implementation doesn't even achieve its purpose, so I did not add a method to return the old hash behaviour. --- src/main/java/sevenUnits/unit/LinearUnit.java | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) (limited to 'src/main/java/sevenUnits/unit/LinearUnit.java') diff --git a/src/main/java/sevenUnits/unit/LinearUnit.java b/src/main/java/sevenUnits/unit/LinearUnit.java index 3c3703c..d453a43 100644 --- a/src/main/java/sevenUnits/unit/LinearUnit.java +++ b/src/main/java/sevenUnits/unit/LinearUnit.java @@ -226,6 +226,19 @@ public final class LinearUnit extends Unit { if (!(obj instanceof LinearUnit)) return false; final LinearUnit other = (LinearUnit) obj; + return Objects.equals(this.getBase(), other.getBase()) + && Double.compare(this.getConversionFactor(), + other.getConversionFactor()) == 0; + } + + /** + * @return true iff this unit and other are equal, + * ignoring small differences caused by floating-point error. + * + * @apiNote This method is not transitive, + * so it cannot be used as an equals method. + */ + public boolean equalsApproximately(final LinearUnit other) { return Objects.equals(this.getBase(), other.getBase()) && DecimalComparison.equals(this.getConversionFactor(), other.getConversionFactor()); @@ -247,7 +260,7 @@ public final class LinearUnit extends Unit { @Override public int hashCode() { return 31 * this.getBase().hashCode() - + DecimalComparison.hash(this.getConversionFactor()); + + Double.hashCode(this.getConversionFactor()); } /** -- cgit v1.2.3