简体   繁体   English

Java 不同参数类型(数字)但算法相同的过载

[英]Java overload on different parameter type (numeric) but same algorithm

I'm currently has several methods to compare two numbers.我目前有几种方法来比较两个数字。 They are exact same algorithm, just different parameter types.它们是完全相同的算法,只是参数类型不同。 However, overloading seems too many copy paste.但是,重载似乎复制粘贴太多。

Current code:当前代码:

    private boolean isFieldUpdateAllowed(float existingData, float submittedData) {
        if (existingData > 0 && submittedData <= 0) {
            return false;
        }

        if (existingData <= 0 && submittedData > 0) {
            return true;
        }

        if (existingData > 0 && submittedData > 0 && existingData != submittedData) {
            return true;
        }

        return false;
    }

    private boolean isFieldUpdateAllowed(int existingData, int submittedData) {
        if (existingData > 0 && submittedData <= 0) {
            return false;
        }

        if (existingData <= 0 && submittedData > 0) {
            return true;
        }

        if (existingData > 0 && submittedData > 0 && existingData != submittedData) {
            return true;
        }

        return false;
    }

// other numeric type comparison

Any way to simplify the code?有什么办法可以简化代码?

ah yes, silly me... thanks.啊,是的,我很傻...谢谢。 Using double is good.使用double是好的。

No. Wait.不,等等。 Not so fast.没那么快。

For the integral types, yes, you can replace all of the overloads with a method with long argument types.对于整数类型,是的,您可以用具有long参数类型的方法替换所有重载。 Other integral types can all be converted to long without any loss of information, and the comparisons will work as expected.其他整数类型都可以转换为long而不会丢失任何信息,并且比较将按预期进行。

But there is a gotcha when we get to double .但是当我们double时有一个问题。

The problem is that a double only has 53 binary bits of precision.问题是double精度只有 53 个二进制位。 So when you convert a large enough long value to a double you get a number that is not mathematically equal to the original value.因此,当您将足够大的long值转换为double时,您会得到一个在数学上不等于原始值的数字。

So when compare this:所以当比较这个时:

    if (existingData > 0 && submittedData > 0 && existingData != submittedData) {
        return true;
    }

in the long and double cases, for some argument values, the != test with long values will be true , but with the converted double values it will be false ... because of the loss of precision in the conversion.longdouble情况下,对于某些参数值,带有long值的!=测试将为true ,但对于转换后的double值,它将为false ...因为转换中的精度损失。

In short, you have to have overloads for both long and double , or you risk getting incorrect results in some cases.简而言之,您必须对longdouble都进行重载,否则在某些情况下您可能会得到不正确的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM