Ich möchte alle Zahlentypen so vergleichen, dass sie gleich sind, wenn sie numerisch ähnlich sind. Wenn der Instanztyp nicht Number ist, wird nur Object.equals() verglichen.
Ich kann sehen, dass der CustomValueComparator registriert wird. Allerdings wird die Methode „equals“ nicht übernommen, wenn ich das Debug in der Methode „equals“ von PrimitiveOrValueType durchführe. Ich sehe keinen valueCompartor für ValueType für Object.class.
Ich kann diese Map nicht zu einer Map machen, da es möglicherweise auch andere Datentypen gibt.
Folgend ist der Code.
Code: Select all
public class NumericComparator implements CustomValueComparator {
//Tolerance for numeric comparison - numbers within this difference are considered equal
private static final double TOLERANCE = 0.01;
@Override
public boolean equals(Object a, Object b) {
// Both null - equal
if (a == null && b == null) {
return true;
}
// One null - not equal
if (a == null || b == null) {
return false;
}
// Both are Numbers - apply tolerance comparison
if (a instanceof Number && b instanceof Number) {
return compareNumbersWithTolerance(a, b);
}
// Not both numbers - use standard Object equality
return a.equals(b);
}
public String toString(Object value) {
return value == null ? "null" : value.toString();
}
/**
* Compares two numbers for numeric equality with tolerance.
* Handles special cases like NaN and Infinity.
*
* @param a First number
* @param b Second number
* @return true if numerically equal within tolerance
*/
private boolean compareNumbersWithTolerance(Object a, Object b) {
// Cast to Number since this method is only called when both are instanceof Number
Number numA = (Number) a;
Number numB = (Number) b;
// Handle special floating point values
if (isSpecialFloatingPoint(numA) || isSpecialFloatingPoint(numB)) {
return handleSpecialFloatingPoint(numA, numB);
}
// Convert both to BigDecimal for precise comparison
try {
BigDecimal bdA = toBigDecimal(numA);
BigDecimal bdB = toBigDecimal(numB);
// Calculate absolute difference
BigDecimal difference = bdA.subtract(bdB).abs();
BigDecimal toleranceBD = BigDecimal.valueOf(TOLERANCE);
// Compare: |a - b|
Mobile version