java 如何使用toArray()方法从二维数组创建2个number[]数组[已关闭]

3vpjnl9f  于 2023-01-04  发布在  Java
关注(0)|答案(2)|浏览(133)

7天前关闭。
这篇文章是23小时前编辑并提交审查的。
Improve this question
我想从toArray()方法返回的2d数组创建2个单独的number []数组,以便用作Statistics:getCorrelation()方法的参数。

double[][] arr = series.toArray();
qoefvg9y

qoefvg9y1#

二维数组只是嵌套在数组中的一组数组。这意味着每个数组索引都是一个项目数组。因此,您可以轻松地将索引的值提取到它自己的数组中。

double[][] my2dArray = {{1,2,3,4,5,6},{1,2,3,4,5,6}};
        
double[] myFirstArray = my2dArray[0];
double[] mySecondArray = my2dArray[1];

这将为您提供2个数组,每个数组包含{1, 2, 3, 4, 5, 6}

8yparm6h

8yparm6h2#

它可能是这样的(阅读评论):

double[][] my2dArray = {{1, 2, 3, 4, 5, 6}, {7, 8, 9, 10, 11, 12}};
            
double[] myFirstArray = new double[my2dArray.length];
double[] mySecondArray = new double[my2dArray.length];
    
int idxCnt = 0;  // new arrays index incrementer.
// Get each array in the matrix one at a time:
for (double[] ary : my2dArray) {
    myFirstArray[idxCnt] = ary[0];  // Get the first column value from current inner Array.
    mySecondArray[idxCnt] = ary[1]; // Get the second column value from current inner Array.
    idxCnt++;                       // increment index for new Arrays.
    // continue loop to get next array from matrix.
}
    
System.out.println("myFirstArray[] contains:  -> " + Arrays.toString(myFirstArray));
System.out.println("mySecondArray[] contains: -> " + Arrays.toString(mySecondArray));

如果运行,控制台窗口应显示:

myFirstArray[] contains:  -> [1.0, 7.0]
mySecondArray[] contains: -> [2.0, 8.0]

相关问题