在Java中将int数组的内容复制到double数组?

bin*_*101 7 java arrays double casting

我正在尝试将我的int数组的内容复制到double类型的数组中.我必须先把它们扔掉吗?

我成功地将int类型的数组复制到另一个int类型的数组中.但是现在我想编写将内容从Array复制A到Array Y(int到double)的代码.

这是我的代码:

public class CopyingArraysEtc {

    public void copyArrayAtoB() {
        double[] x = {10.1,33,21,9},y = null;
        int[] a = {23,31,11,9}, b = new int[4], c;

        System.arraycopy(a, 0, b, 0, a.length);

        for (int i = 0; i < b.length; i++)
        {
            System.out.println(b[i]);
        }

    }          

    public static void main(String[] args) {
        //copy contents of Array A to array B
        new CopyingArraysEtc().copyArrayAtoB();
    }
}
Run Code Online (Sandbox Code Playgroud)

Mur*_*nik 20

值得一提的是,在这个时代,Java 8提供了一个优雅的单行程,无需使用第三方库:

int[] ints = {23, 31, 11, 9};
double[] doubles = Arrays.stream(ints).asDoubleStream().toArray();
Run Code Online (Sandbox Code Playgroud)


Koe*_*err 13

System.arraycopy()无法复制int[]double[]

如何使用谷歌番石榴:

int[] a = {23,31,11,9};

//copy int[] to double[]
double[] y=Doubles.toArray(Ints.asList(a));
Run Code Online (Sandbox Code Playgroud)


Bhe*_*ung 9

您可以遍历源的每个元素并将它们添加到目标数组.你不需要一个明确的演员int,double因为double它更广泛.

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

你可以制作这样的实用方法 -

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;
}
Run Code Online (Sandbox Code Playgroud)


Psh*_*emo 6

来自System.arraycopy JavaDoc

[...]否则,如果满足以下任何条件,则抛出ArrayStoreException并且不修改目标:

*...

*...

*src参数和dest参数引用其组件类型为不同基本类型的数组.[...]

由于intdouble不同的原始类型,您必须手动迭代一个数组并将其内容复制到另一个数组.