0

为什么以下代码会引发异常,这是什么意思?

float[][] foo_array = new float[WIDTH][HEIGHT]; //Assume WDITH and Height are defined
java.util.Arrays.fill(foo_array, Float.POSITIVE_INFINITY);

如您所见,我只是试图将浮点数组初始化为无穷大,但这会导致以下异常:

Exception in thread "LWJGL Application" com.badlogic.gdx.utils.GdxRuntimeException: java.lang.ArrayStoreException: java.lang.Float
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:113)
Caused by: java.lang.ArrayStoreException: java.lang.Float
at java.util.Arrays.fill(Arrays.java:2170)

当然,我可以遍历整个数组并将每个值设置为无穷大,而且我知道无论如何填充方法都是这样做的(它还能如何工作)。但我只是好奇为什么这不起作用以及这个例外是什么。

编辑:我省略了异常消息的很大一部分,因为我不想让它这么长而且它没有提供任何相关信息。

4

4 回答 4

3

As per JLS 10.5

If the type of the value being assigned is not assignment-compatible (§5.2) with the component type, an ArrayStoreException is thrown.

It seems that your distMap reference is not a float[] , may be a float[][] which will not work , because float[] is not equivalent to float[][].

Try with a correct parameter like foo_array[0] , it works:

float[][] foo_array = new float[10][10]; //Assume WDITH and Height are defined
java.util.Arrays.fill(foo_array[0], Float.POSITIVE_INFINITY);
System.out.println(Arrays.toString(foo_array));

Also look at the method signature of fill(float[] a, float val).

You need to iterate through foo_array and set each foo_array[i] . Sample :

for(float[] floatArrays:foo_array) {
    java.util.Arrays.fill(floatArrays, Float.POSITIVE_INFINITY);
}

Here is a nice tutorial on multi-dimensional arrays.

enter image description here

于 2013-08-03T15:41:45.220 回答
2

foo_array is a float[][], which makes it clear why your attempt fails: the element type of foo_array is float[]. That's how Java's multidimensional arrays work: they are arrays of arrays.

To correct your problem, iterate over all float[]-typed members of foo_array and use Arrays.fill against each of them.

于 2013-08-03T15:44:06.693 回答
2

看来你应该使用这个循环来做你想做的事:

for(int i = 0; i < foo_array.length; i++){
   Arrays.fill(foo_array[i], Float.POSITIVE_INFINITY);
}
于 2013-08-03T15:47:26.790 回答
0

您的代码将在 java.util.Arrays 中调用以下方法 因此您的异常符合预期。
public static void fill(Object[] a, Object val) {
for (int i = 0, len = a.length; i < len; i++)
a[i] = val;
}

于 2013-08-03T16:18:47.797 回答