我正在尝试将我的int数组的内容复制到double类型的数组中。我必须先把它们抛出来吗?
我成功地将int类型的数组复制到另一个int类型的数组中。
但是现在我想编写将内容从数组A
复制到数组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();
}
}
答案 0 :(得分:19)
值得一提的是,在这个时代,Java 8提供了一个优雅的单行程,无需使用第三方库:
int[] ints = {23, 31, 11, 9};
double[] doubles = Arrays.stream(ints).asDoubleStream().toArray();
答案 1 :(得分:13)
System.arraycopy()
无法将int[]
复制到double[]
如何使用google guava:
int[] a = {23,31,11,9};
//copy int[] to double[]
double[] y=Doubles.toArray(Ints.asList(a));
答案 2 :(得分:8)
您可以遍历源的每个元素并将它们添加到目标数组。您不需要从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;
}
答案 3 :(得分:6)
[...]否则,如果满足以下任何条件,则抛出 ArrayStoreException 并且不修改目标:
... *
... *
* src参数和dest参数引用其组件类型为不同基元类型的数组。 [...]
由于int
和double
是不同的基本类型,因此您必须手动迭代一个数组并将其内容复制到另一个数组。