Arrays.fill with multidimensional array in Java

后端 未结 13 1816
心在旅途
心在旅途 2020-11-27 18:49

How can I fill a multidimensional array in Java without using a loop? I\'ve tried:

double[][] arr = new double[20][4];
Arrays.fill(arr, 0);

13条回答
  •  难免孤独
    2020-11-27 19:14

    The OP asked how to solve this problem without a loop! For some reason it is fashionable these days to avoid loops. Why is this? Probably there is a realization that using map, reduce, filter, and friends, and methods like each hide loops and cut down on program verbage and are kind of cool. The same goes for really sweet Unix pipelines. Or jQuery code. Things just look great without loops.

    But does Java have a map method? Not really, but we could define one with a Function interface with an eval or exec method. It isn't too hard and would be a good exercise. It might be expensive and not used in practice.

    Another way to do this without a loop is to use tail recursion. Yes, it is kind of silly and no one would use it in practice either, but it does show, maybe, that loops are fine in this case. Nevertheless, just to show "yet another loop free example" and to have fun, here is:

    import java.util.Arrays;
    public class FillExample {
        private static void fillRowsWithZeros(double[][] a, int rows, int cols) {
            if (rows >= 0) {
                double[] row = new double[cols];
                Arrays.fill(row, 0.0);
                a[rows] = row;
                fillRowsWithZeros(a, rows - 1, cols);
            }
        }
    
        public static void main(String[] args) {
            double[][] arr = new double[20][4];
            fillRowsWithZeros(arr, arr.length - 1, arr[0].length);
            System.out.println(Arrays.deepToString(arr));
        }
    }
    

    It isn't pretty, but in answer to the OP's question, there are no explicit loops.

提交回复
热议问题