1

好的,这是一个非常简单的问题,我对此感到很困惑……但是这让我很头疼。这是来源:

import java.util.Arrays;
public class InputValues {  
    public int[] myarrayvar;
    public InputValues(int[] myarraypass) {     
    ---- help here
    }
    public void init() {        
    ---help here
    }
    public int[] getmyarrayvar() {
        return myarrayvar;
    }
    public void setmyarrayvar(int[] myarraypass) {
        this.myarrayvar= mayarraypass;
    }
}

我称之为

InputValues inputValues = new InputValues(myarraypass);
inputValues.init();

myarraypass 是 int[] 类型。

就像我说的那样,这应该很容易......但由于某种原因我无法让它工作......

4

2 回答 2

1

您可以尝试以下操作:

  1. 将实例变量访问权限从 更改publicprivate

  2. 在构造函数中,您可以使用以下行:

    this.myarrayvar = myarraypass;

但是请记住,如果myarraypass在课堂外修改InputValuesmyarrayvar也会受到影响。

如果您不希望发生这种行为,则应逐个索引复制。

this.myarrayvar = new int[myarraypass.length];
for(int i=0; i<myarraypass.length;i++)
    this.myarrayvar[i] = myarraypass[i];

或者

this.myarrayvar = (int[]) myarraypass.clone();

或者

this.myarrayvar = new int[myarraypass.length];
System.arraycopy(myarraypass, 0, this.myarrayvar, 0, myarraypass.length);
于 2012-10-19T09:38:58.530 回答
1
  1. In case your myarrayvar is public then why would you need a setter and getter. You need them only when your member is inaccessible to the outside world, i.e. it's marked private.
  2. Nest, you can use the following in your constructor for setting the array,
public InputValues(int[] myarraypass) { 

    this.myarrayvar = new int[myarraypass.length];    

    System.arraycopy(myarraypass, 0, this.myarrayvar, 0, myarraypass.length );

}
于 2012-10-19T09:44:02.717 回答