Combining Java Functions without Overloading

时间:2016-04-04 18:37:24

标签: java function overloading

How would I combine these two functions to make my code more efficient? I am currently just overloading the functions to allow for integers and strings to be accepted as arguments.

private void flushGrid(int grid[][], int replacement) {
        for(int x=0;x<grid.length;x++) {
            for(int y=0;y<grid[0].length;y++) {
                grid[x][y] = replacement;
            }
        }
    }

private void flushGrid(String grid[][], String replacement) {
    for(int x=0;x<grid.length;x++) {
        for(int y=0;y<grid[0].length;y++) {
           grid[x][y] = replacement;
        }
    }
}

2 个答案:

答案 0 :(得分:3)

Combining these two methods won't make it simpler or more efficient but you can do it.

private void flushGrid(Object[] grid, Object replacement) {
    for (int x = 0; x < grid.length; x++) {
        for (int y = 0; y < Array.getLength(grid[0]); y++) {
            Array.set(grid[x], y, replacement);
        }
    }
}

Note this works with primitive arrays as well as reference arrays.

答案 1 :(得分:1)

You could make your method generic on type T. Something like,

private <T> void flushGrid(T grid[][], T replacement) {
    for (int x = 0; x < grid.length; x++) {
        for (int y = 0; y < grid[0].length; y++) {
            grid[x][y] = replacement;
        }
    }
}

which would work with String, Integer or any other reference type (but not primitive types like int, long or double).

相关问题