creating and returning an array from a method
36,417
Not sure what is the problem. You mean this?
public int[] myMethod() {
//...
int[] res = new int[7];
//... set values ...
return res;
}
Author by
Troy
Updated on April 04, 2020Comments
-
Troy about 4 years
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?
-
Troy about 14 yearsThat'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.
-
Andrea Polci about 14 yearsWill create a new array everytime. To reuse the same array create it ouside the method and pass the same instance at every call.
-
Phil about 14 years@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).