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;
}
}
}
答案 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
).