如何将原始的双精度浮点数数组转换为双精度浮点数对象数组。

3
使用Apache common math库,我可以获得一个原始的double类型数组。
  RealMatrix pInverse = new LUDecomposition(p).getSolver().getInverse();

  double[][] temp = pInverse.getData();

我需要将温度转换为一个Double[][]

  Double[][] inverse = new Double[][]temp;

5
我很确定,唯一的方法是逐个复制数组元素,并在此过程中进行装箱。这是件麻烦的事情,但编写一个能够完成此操作的小方法应该不难。 - markspace
"我需要将temp转换为Double[][]。" 那么是什么阻止您确切地这样做呢? - Andreas
@DCR 请查看第一条评论:逐个元素转换。即使有更好的方法,也不应该阻止您尝试。你的问题只是说:“我需要...”,隐含着“我懒得自己尝试一下”。 - Andreas
非常密切相关,但方向相反:https://stackoverflow.com/questions/37714550/how-do-you-convert-a-two-dimensional-array-of-a-boxed-type-to-a-two-dimensional - Hulk
@Kröw 谢谢。事实上,我确实尝试过 Double[][] inverse = new Double[][]temp;,当然它没有起作用。对我来说,这似乎很奇怪,需要逐个元素地进行操作。 - DCR
显示剩余3条评论
3个回答

17

如果您正在使用Java 8+,则可以使用:

Double[][] inverse = Arrays.stream(temp)
        .map(d -> Arrays.stream(d).boxed().toArray(Double[]::new))
        .toArray(Double[][]::new);

你能分解这个语法并解释一下正在发生什么吗?为什么我们不能直接在temp上使用map函数,::是什么意思?另外,为什么要两次使用toArray方法? - DCR
@DCR 我想分享一些链接,使您了解正在发生的事情,首先看一下这个http://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/ 和::(双冒号)在Java 8中的操作符。此外,我使用了两个toArray,第一个是收集每个单一数组的装箱结果,第二个是将结果收集到一个数组中,希望可以给您一个全局的想法 :) - Youcef LAIDANI
1
流和Lambda似乎是处理这个问题的最佳方式。接受的答案并没有错,但这种方法更易于阅读。 - ViaTech

9

由于您已经在使用Apache Commons,所以值得指出ArrayUtils.toObject

将原始double数组转换为对象。

使用它,您可以编写Andreas第一种解决方案

Double[][] inverse = new Double[temp.length][];
for (int i = 0; i < temp.length; i++) {
    inverse[i] =  ArrayUtils.toObject(temp[i]);
}

或者使用YCF_L的解决方案(请参考此链接)。
Double[][] inverse = Arrays.stream(temp)
    .map(ArrayUtils::toObject)
    .toArray(Double[][]::new);

7

这是一组简单的嵌套循环:

Double[][] inverse = new Double[temp.length][];
for (int i = 0; i < temp.length; i++) {
    inverse[i] = new Double[temp[i].length];
    for (int j = 0; j < temp[i].length; j++)
        inverse[i][j] = temp[i][j];
}

如果您知道所有子数组的大小相同,则甚至更短:

Double[][] inverse = new Double[temp.length][temp[0].length];
for (int i = 0; i < temp.length; i++)
    for (int j = 0; j < temp[0].length; j++)
        inverse[i][j] = temp[i][j];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接