Copy contents of an int array to a double array in Java?

前端 未结 4 1504
无人及你
无人及你 2021-01-04 20:35

I\'m trying to copy the contents of my int array into an array of type double. Do I have to cast them first?

I successfully copied an array of type int to another a

相关标签:
4条回答
  • 2021-01-04 21:03

    You can iterate through each element of the source and add them to the destination array. You don't need an explicit cast going from int to double because double is wider.

    int[] ints = {1, 2, 3, 4};
    double[] doubles = new double[ints.length];
    for(int i=0; i<ints.length; i++) {
        doubles[i] = ints[i];
    }
    

    You can make a utility method like this -

    public static double[] copyFromIntArray(int[] source) {
        double[] dest = new double[source.length];
        for(int i=0; i<source.length; i++) {
            dest[i] = source[i];
        }
        return dest;
    }
    
    0 讨论(0)
  • 2021-01-04 21:09

    Worth mentioning that in this day and age, Java 8 offers an elegant one-liner to do this without the need to use third-party libraries:

    int[] ints = {23, 31, 11, 9};
    double[] doubles = Arrays.stream(ints).asDoubleStream().toArray();
    
    0 讨论(0)
  • 2021-01-04 21:15

    System.arraycopy() can't copy int[] to double[]

    How about using google guava:

    int[] a = {23,31,11,9};
    
    //copy int[] to double[]
    double[] y=Doubles.toArray(Ints.asList(a));
    
    0 讨论(0)
  • 2021-01-04 21:27

    From System.arraycopy JavaDoc

    [...] Otherwise, if any of the following is true, an ArrayStoreException is thrown and the destination is not modified:

    *...

    *...

    *The src argument and dest argument refer to arrays whose component types are different primitive types. [...]

    Since int and double are different primitive types you will have to manually iterate through one array and copy its content to another one.

    0 讨论(0)
提交回复
热议问题