1

Ok this is a guess a really simple problem which I am having a black out about.... however it is killing my head. Here is the source:

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;
    }
}

I call the this with

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

myarraypass is of type int[].

Like I said this should be really easy.... but I can't get it to work for some reason....

1
  • In what sense you cannot get it work? What is the problem you have encountered? Commented Oct 19, 2012 at 9:48

2 Answers 2

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 );

}
Sign up to request clarification or add additional context in comments.

Comments

1

You can try following things:

  1. Change the instance variable access from public to private.

  2. in constructor you can use following line:

    this.myarrayvar = myarraypass;

But remember, if myarraypass is modified outside class InputValues, myarrayvar will also be affected.

If you don't want that behavior to occur, you should copy index-by-index.

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

OR

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

OR

this.myarrayvar = new int[myarraypass.length];
System.arraycopy(myarraypass, 0, this.myarrayvar, 0, myarraypass.length);

2 Comments

I did 1. and inserted a print cmd in the setter... but that is never printing .. so I guess it is never called and I use the array to do a calc later and that returns a NullPointerException. for some reason the var is not set.
Got it to work.. I placed the source way out of brakets... works fine now that I did that right.. :-) Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.