在Java多维数组Arrays

在Java多维数组Arrays

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

问题描述

我怎么能不填写使用循环在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中的

在此先感谢!

推荐答案

这是因为双击[] [] 的数组双[] 你不能分配 0.0 来(它会像做双击[] =矢量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中的默认值,从而矩阵实际上已经被填充零,当你从。不过,如果你想用,填补好说, 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);

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

09-03 01:49