Java array listing

I am looking for an array intfor double.

so when i

int arr[] = {1, 2, 3}; 

I want to use arr, say, pass it as a parameter double[] to a method.

What is the best way to do this?

cast

(double[])arr

does not work.

i can iterate arr:

double[] dblA = new double[arr.length];
int ind=0; 
for (int x:arr)
    dblA[ind++]=x;   // (double)x; 

Is there a better way to do this?

System.arraycopy does not do this - does not work on arrays of two different primitive types.

Note: saw "Moving an object to an array in Java" and some other discussions.

TIA.

+4
source share
2 answers

Using Java 7 or below is not easy, you just have to manually copy them.

Java 8, ( ), , :

int[] intArray = {1, 2, 3};
double[] doubleArray = Arrays.stream(intArray)
    .mapToDouble(i -> i)
    .toArray();

IntStream, DoubleStream IntToDoubleFunction, int i double i. , toArray

+2

Java 8 , :

package com.java.se.stackoverflow;

import java.util.Arrays;

public class ArrayCast {

    public static void main(String[] argv) throws Exception {
        int[] inputArray = new int[]{23, 4, 5, 6, 89};
        double[] outputArray = new double[inputArray.length];
        Arrays.setAll(outputArray, inputArrayIndex -> (double) inputArray[inputArrayIndex]);

        System.out.println(Arrays.toString(outputArray));

    }

}
+1

All Articles