2

i currently have a method that checks what is around the centre item in a 3x3 grid, if what is in the 8 adjacent positions is containing what i am checking for i want to mark that square on an array with length 7 as being 1.

to do this i need to create and return an array in my method, is it possible to do this?

2 Answers 2

4

Not sure what is the problem. You mean this?

public int[] myMethod() {
 //...
 int[] res = new int[7];
 //... set values ...
 return res;
}
Sign up to request clarification or add additional context in comments.

3 Comments

That's it! Thanks. A quick question though... will this make a new array everytime I run it, or can I re-use the same array over and over again, the main program is running on an endless loop and will have to run this method 1600 times for each run through the loop.
Will create a new array everytime. To reuse the same array create it ouside the method and pass the same instance at every call.
@Troy: If that's the case, you may want to make the array static (just make sure to set every index each time through, because old values will still be there). However, if you throw away the array when you are done with it (declaring your array within the same loop you call the method from), then don't worry - Java's GC will take care of the memory, and you just have some extra object creation going on (probably not a big issue, but profile if unsure).
0

Declare the return type to be two dimensional array (int[][]), create the array in your method and return that.

public int[][] getArray() {
  int[][] myArray = new int[3][3];
  // Populate array
  return myArray;
}

Comments

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.