我正在尝试将 int 数组的内容复制到 double 类型的数组中。我必须先投射它们吗?
我成功地将一个 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();
}
}
值得一提的是,在当今时代,Java 8 提供了一个优雅的单行代码来完成此任务,而无需使用第三方库:
int[] ints = {23, 31, 11, 9};
double[] doubles = Arrays.stream(ints).asDoubleStream().toArray();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)