`
iloveflower
  • 浏览: 76756 次
社区版块
存档分类
最新评论
  • iloveflower: 呵呵。好好学习。。。。。。。。。。。。
    java 读书
  • Eric.Yan: 看了一点,不过是电子版的……你这一说到提醒我了,还要继续学习哈 ...
    java 读书

Arrays.fill with multidimensional array in Java

阅读更多
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); 

 This results in java.lang.ArrayStoreException: java.lang.Double

Thanks in advance!

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.


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics