int数组的内容复制到Java中的双阵列? [英] Copy contents of an int Array to a double Array in Java?

查看:117
本文介绍了int数组的内容复制到Java中的双阵列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我的int数组中的内容复制到double类型的数组。我必须先投呢?

我成功复制int类型的数组类型为int的另一个数组。
不过现在我想写code,它会从Array A 内容复制到阵列(INT翻番)。

下面是我的code:

 公共类CopyingArraysEtc {    公共无效copyArrayAtoB(){
        双[] X = {} 10.1,33,21,9,Y = NULL;
        INT []α= {23,31,11,9},B =新INT [4],C。;        System.arraycopy(一,0,B,0,则为a.length);        的for(int i = 0; I< b.length个;我++)
        {
            的System.out.println(B [I]);
        }    }    公共静态无效的主要(字串[] args){
        //复制到排列B数组a的内容
        新CopyingArraysEtc()copyArrayAtoB()。
    }
}


解决方案

您可以通过源中的每个元素进行迭代,并将它们添加到目标数组。你并不需要双击,因为双击 INT 去C $ C>更广。

  INT [] =整数{1,2,3,4};
双[] =双打新的双[ints.length]
的for(int i = 0; I< ints.length;我++){
    双打[I] =整数[I]
}

您可以做一个实用的方法是这样 -

 公共静态双重[] copyFromIntArray(INT []源){
    双[] = DEST新的双[source.length]
    的for(int i = 0; I< source.length;我++){
        DEST [I] =源[I]
    }
    返回DEST;
}

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 array of type int. However now I want to write code that would copy contents from Array A to Array Y (int to double).

Here is my code:

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();
    }
}

解决方案

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;
}

这篇关于int数组的内容复制到Java中的双阵列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆