我尝试将int数组的内容复制到一个双精度类型的数组中。我是不是必须先对他们进行选角?
我成功地将一个int类型的数组复制到另一个int类型的数组中。但是,现在我想编写代码,将内容从数组A复制到数组Y (整型为双精度)。
下面是我的代码:
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();
}
}发布于 2012-10-04 22:18:48
您可以遍历源的每个元素并将它们添加到目标数组中。您不需要从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];
}你可以像这样做一个实用的方法-
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;
}发布于 2016-03-07 06:15:40
值得一提的是,在当今时代,Java 8提供了一个优雅的单行程序来完成此任务,而无需使用第三方库:
int[] ints = {23, 31, 11, 9};
double[] doubles = Arrays.stream(ints).asDoubleStream().toArray();发布于 2012-10-04 22:31:49
System.arraycopy()无法将int[]复制到double[]
使用google guava怎么样:
int[] a = {23,31,11,9};
//copy int[] to double[]
double[] y=Doubles.toArray(Ints.asList(a));https://stackoverflow.com/questions/12729139
复制相似问题