[英]Trouble performing a deep copy of array
Need some advice for a project in an intro Java class. 需要一些关于简介Java类中的项目的建议。 I'm stuck at creating a assignment constructor which takes an array as input and completes a deep copy.
我坚持创建一个赋值构造函数,它将数组作为输入并完成深度复制。 The constructor in question is found in the second block of code.
有问题的构造函数位于第二个代码块中。
import java.util.Scanner;
public class NumberList
{
public static final int MAX_CAPACITY = 100;
private double [] numbers;
private int length;
public NumberList()
{
numbers = new double[MAX_CAPACITY];
int i;
for(i = 0; i < MAX_CAPACITY; i++)
numbers[i] = 0;
length = 10;
}
Everything before this line compiles. 此行之前的所有内容都会编译。 The constructor below is to complete a deep copy from the array parameter to the numbers array.
下面的构造函数是完成从数组参数到数字数组的深层复制。
NumberList(final double a[])
{
double a[] = new double[MAX_CAPACITY];
numbers = a[];
}
Following errors received: 收到以下错误:
NumberList.java:67: error: '.class' expected
numbers = a[];
For the life of me, I cannot figure out how to do fix this. 对于我的生活,我无法弄清楚如何解决这个问题。 I've tried with a "for" loop, as well.
我也尝试过“for”循环。
Just run over a
and copy its elements to numbers
: 只需运行
a
并将其元素复制到numbers
:
public NumberList(final double[] a) {
this.numbers = new double[a.length];
for (int i = 0; i < a.length; ++i) {
this.numbers[i] = a[i];
}
}
NumberList(final double a[])
{
double a[] = new double[MAX_CAPACITY];
numbers = a[];
}
The first line is attempting to re-declare the parameter a
; 第一行是试图重新声明参数
a
; you can't do that. 你不能这样做。
And the second line uses an invalid syntax: you never use []
except in the declaration of array variables, or the initialization of those variables. 第二行使用了无效的语法:除了数组变量的声明或这些变量的初始化之外,你永远不会使用
[]
。
The easiest way to copy a
is to write: 复制
a
的最简单方法是写:
numbers = Arrays.copyOf(a, a.length);
But you can write this with a loop like Mureinik shows you. 但是你可以像Mureinik给你的那样用循环来写这个。
Note that you should write double[] a
, not double a[]
. 请注意,您应该编写
double[] a
,而不是double a[]
。 The two are semantically identical, but the former is preferred because []
is part of the type, not the variable name. 两者在语义上是相同的,但前者是首选,因为
[]
是类型的一部分,而不是变量名称。
The double a[]
-style was put into Java "as a nod to the tradition of C and C++" . double a[]
式被用于Java “作为对C和C ++传统的点头” 。 You can read more here . 你可以在这里阅读更多。
You can simply use: 你可以简单地使用:
NumberList(final double[] a) {
numbers = Arrays.copyOf(a, a.length);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.