编程语言
首页 > 编程语言> > 重用代码 – Java

重用代码 – Java

作者:互联网

有没有办法在这些函数中重用迭代数组代码:

public static double[] ln(double[] z) {
    // returns  an array that consists of the natural logarithm of the values in array z
    int count = 0;

    for (double i : z){
        z[count] = Math.log(i);
        count += 1;
    }
    return z;
}


public static double[] inverse(double[] z) {
    //  returns  an array that consists of the inverse of the values in array z
    int count = 0;

    for (double i : z){
        z[count] = Math.pow(i,-1);
        count += 1;
    }
    return z;
}

解决方法:

是的,使用http://en.wikipedia.org/wiki/Strategy_pattern,但它可能是一个矫枉过正.重复的迭代和计数看起来并不那么糟糕.

标签:java,function,operator-overloading,code-reuse
来源: https://codeday.me/bug/20190713/1447932.html