Arrays.fill 用 Ja​​va 中的多维数组 [英] Arrays.fill with multidimensional array in Java

查看:25
本文介绍了Arrays.fill 用 Ja​​va 中的多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在不使用循环的情况下在 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);

这导致 java.lang.ArrayStoreException: java.lang.Double

推荐答案

这是因为 double[][] 是一个 double[] 的数组,你可以'不要将 0.0 分配给(这就像执行 double[] vector = 0.0).事实上,Java 没有真正的多维数组.

This is because a double[][] is an array of double[] which you can't assign 0.0 to (it would be like doing double[] vector = 0.0). In fact, Java has no true multidimensional arrays.

碰巧的是,0.0 是 Java 中 doubles 的默认值,因此当您从 new 获取矩阵时,该矩阵实际上已经填充了零.但是,如果您想用 1.0 填充它,您可以执行以下操作:

As it happens, 0.0 is the default value for doubles in Java, thus the matrix will actually already be filled with zeros when you get it from new. However, if you wanted to fill it with, say, 1.0 you could do the following:

我不认为 API 提供了一种无需循环即可解决此问题的方法.然而,使用 for-each 循环来完成它很简单.

I don't believe the API provides a method to solve this without using a loop. It's simple enough however to do it with a for-each loop.

double[][] matrix = new double[20][4];

// Fill each row with 1.0
for (double[] row: matrix)
    Arrays.fill(row, 1.0);

这篇关于Arrays.fill 用 Ja​​va 中的多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆