The shortest way to make an array 2d int in 2d double

I have a method that only gets double[][]to which I would like to go to int[][], is there a short way to do this in java, something simple:

int [][] iArray = {
          { 1, 2, },
          { 5, 6, }
        };
double [][] dArray = (double[][]) iArray ; ???
+5
source share
6 answers

Unfortunately, the only way to make your array is to iterate over each element and select it one by one, reinserting it into a new array double[][].

No shortcut.

+18
source

No, this is the wrong typing. int [] is a type and double [] is a type, and they are not related, so such assignments are not allowed. Therefore, there is no way to do this.

You will need to copy the elements (you can assign an int to the double without casting).

+2

, -, ints, .

EDIT: double int, .

0

:

    int[][] intarray = {{1, 2}, {5, 6}};

    double[][] doublearray = new double[intarray.length][intarray[0].length];

    for(int i = 0; i < intarray.length; i++)
    {
        for(int j = 0; j < intarray[0].length; j++)
            doublearray[i][j] = (double) intarray[i][j];
    }

: Andreas_D, , , , .

0

, , Java 8, , ?

import java.util.Arrays;

// ...

/// Cast!
int[][] int2DArray = {{3, 1}, {3, 3, 7}, {}};
Object[] arrayOfUntypedArraies = Arrays.stream(int2DArray).map(intArray -> Arrays.stream(intArray).asDoubleStream().toArray()).toArray();
double[][] double2DArray = Arrays.copyOf(arrayOfUntypedArraies, arrayOfUntypedArraies.length, double[][].class);

/// Print!
System.out.println(Arrays.deepToString(int2DArray));
// [[1, 2], [5, 6, 7], []]
System.out.println(Arrays.deepToString(double2DArray));
// [[1.0, 2.0], [5.0, 6.0, 7.0], []]
0

Java 8 1- int double:

double[] singleDimensionDoubleArray = 
        Arrays.stream(singleDimensionIntArray).asDoubleStream().toArray()

, , , , :

int[][] iArray = {
    {1, 2,},
    {5, 6,}
};

double[][] dArray = new double[iArray.length][];
for (int row = 0; row < iArray.length; row++) {
    dArray[row] = Arrays.stream(iArray[row]).asDoubleStream().toArray();
}

I was just about to publish this answer, but I thought that I would publish some indicators about how much faster this was a naive cycle over each element. Turns out it was about 10x slower ! I tested it with an array of zeros at 10000x1000. I suppose this is creating an additional object that causes a slowdown.

If someone else cannot prove the opposite, I think the simplest solution is actually the fastest:

for (int row = 0; row < iArray.length; row++) {
    for (int column = 0; column < iArray[0].length; column++) {
        dArray[row][column] = (double) iArray[row][column];
    }
}
0
source

All Articles