0
public class Examples
{
    private int numbers[]; //instance variable
    public Examples()
    {
        numbers = new int[10];
        for (int i = 0; i < numbers.length; i++) 
        {                           //constructor number 1
           numbers[i] = 42;
        }
     } 

     public Examples(int[] array)
     {
        numbers = new int[array.length];
        for (int i = 0; i < array.length; i++) 
        {
           numbers[i] = array[i];         //constructor number 2
        }
      }
}

所以我必须编写一个 set 方法,该方法将为实例变量创建一个新数组,该数组与传递给 setNumbers 的数组长度相同,然后复制其参数的值。

到目前为止,我有

public void setNumbers (int numbers)
    {
        int[] setNumbers = int numbers;
    } 

我从中得到错误,不知道为什么

4

1 回答 1

0

我不知道您的 setter 方法签名应该是什么,但正确的方法可能是其中之一:

public void setNumbers (int []numbers) {
    this.numbers = numbers;
    // or perhaps you need to copy the argument:
    // this.numbers = Arrays.copyOf(numbers, numbers.length);
}

要不然:

public void setNumbers (int numbers) {
    this.numbers = new int[numbers];
}

另外,我会这样写你的构造函数:

public Examples()
{
    numbers = new int[10];
    Arrays.fill(numbers, 42);
 } 

 public Examples(int[] array)
 {
    numbers = Arrays.copyOf(array, array.length);
  }
于 2012-11-07T03:05:14.040 回答