Search code examples
javafunctionoperator-overloadingcode-reuse

Reusing code - Java


Is there any way of reusing the iteration through the array code in these functions:

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;
}

Solution

  • Yes, using http://en.wikipedia.org/wiki/Strategy_pattern but it'll probably be an overkill. A duplicate iteration and count++ doesn't look so bad.