Arrays.fill with multidimensional array in Java

后端 未结 13 1814
心在旅途
心在旅途 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:27

    Don't we all sometimes wish there was a
    void java.util.Arrays.deepFill(T[]…multiDimensional). Problems start with
    Object threeByThree[][] = new Object[3][3];
    threeByThree[1] = null; and
    threeByThree[2][1] = new int[]{42}; being perfectly legal.
    (If only Object twoDim[]final[] was legal and well defined…)
    (Using one of the public methods from below keeps loops from the calling source code.
    If you insist on using no loops at all, substitute the loops and the call to Arrays.fill()(!) using recursion.)

    /** Fills matrix {@code m} with {@code value}.
     * @return {@code m}'s dimensionality.
     * @throws java.lang.ArrayStoreException if the component type
     *  of a subarray of non-zero length at the bottom level
     *  doesn't agree with {@code value}'s type. */
    public static int deepFill(Object[] m, T value) {
        Class components; 
        if (null == m ||
            null == (components = m.getClass().getComponentType()))
            return 0;
        int dim = 0;
        do
            dim++;
        while (null != (components = components.getComponentType()));
        filler((Object[][])m, value, dim);
        return dim;
    }
    /** Fills matrix {@code m} with {@code value}.
     * @throws java.lang.ArrayStoreException if the component type
     *  of a subarray of non-zero length at level {@code dimensions}
     *  doesn't agree with {@code value}'s type. */
    public static void fill(Object[] m, T value, int dimensions) {
        if (null != m)
            filler(m, value, dimensions);
    }
    
    static void filler(Object[] m, T value, int toGo) {
        if (--toGo <= 0)
            java.util.Arrays.fill(m, value);
        else
            for (Object[] subArray : (Object[][])m)
                if (null != subArray)
                    filler(subArray, value, toGo);
    }
    

提交回复
热议问题