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/utils/DecimalComparison.java | 15 --------------- 1 file changed, 15 deletions(-) (limited to 'src/main/java/sevenUnits/utils/DecimalComparison.java') diff --git a/src/main/java/sevenUnits/utils/DecimalComparison.java b/src/main/java/sevenUnits/utils/DecimalComparison.java index 62c3720..03dd15b 100644 --- a/src/main/java/sevenUnits/utils/DecimalComparison.java +++ b/src/main/java/sevenUnits/utils/DecimalComparison.java @@ -69,7 +69,6 @@ public final class DecimalComparison { * @return whether they are equal * @since 2019-03-18 * @since v0.2.0 - * @see #hash(double) */ public static final boolean equals(final double a, final double b) { return DecimalComparison.equals(a, b, DOUBLE_EPSILON); @@ -194,7 +193,6 @@ public final class DecimalComparison { * @param b second value to test * @return whether they are equal * @since 2020-09-07 - * @see #hash(double) */ public static final boolean equals(final UncertainDouble a, final UncertainDouble b) { @@ -236,19 +234,6 @@ public final class DecimalComparison { epsilon); } - /** - * Takes the hash code of doubles. Values that are equal according to - * {@link #equals(double, double)} will probably have the same hash code. - * - * @param d double to hash - * @return hash code of double - * @since 2019-10-16 - */ - // TODO reconsider using this - public static final int hash(final double d) { - return Float.hashCode((float) d); - } - // You may NOT get any DecimalComparison instances private DecimalComparison() { throw new AssertionError(); -- cgit v1.2.3