Java 从方法创建和返回数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2573887/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
creating and returning an array from a method
提问by Troy
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.
我目前有一种方法可以检查 3x3 网格中中心项目周围的内容,如果 8 个相邻位置中的内容包含我正在检查的内容,我想在长度为 7 的数组上将该正方形标记为 1。
to do this i need to create and return an array in my method, is it possible to do this?
为此,我需要在我的方法中创建并返回一个数组,是否可以这样做?
采纳答案by Andrea Polci
Not sure what is the problem. You mean this?
不知道是什么问题。你是这个意思?
public int[] myMethod() {
//...
int[] res = new int[7];
//... set values ...
return res;
}
回答by Oded
Declare the return type to be two dimensional array (int[][]
), create the array in your method and return that.
将返回类型声明为二维数组 ( int[][]
),在您的方法中创建数组并返回该数组。
public int[][] getArray() {
int[][] myArray = new int[3][3];
// Populate array
return myArray;
}