[英]How to store the return of a 2D Array
如何存儲2D數組的返回值? 例如
public Class A{
public String something(){
String []some_array=new String[2];
//stuff in here...sets elements of our array to something
//unsure of the next line
return some_array[];
}
public static void main(String[] args) {
String []some_other_array=new String[2];
A myA=new A();
//unsure of the next line
some_other_array[]=myA.something();
我如何返回返回的數組的第一個第二個元素作為我存儲它的數組的第一個第二個元素?
任何人都可以澄清是否合法使用我的方法中的參數變量something()而不使它們首先等於另一個變量? 我一直以為你要么必須在方法中聲明另一個變量並使其等於參數並使用你創建的新變量。
更改方法的返回類型,如下所示:
public String[] something(){
String []some_array=new String[2];
//stuff in here...sets elements of our arrays to something
return some_array;
}
另請注意,return語句在變量some_array
旁邊沒有[]
括號。
在你的主要方法中你應該這樣寫:
String[] some_other_array;
A myA=new A();
some_other_array = myA.something();
另請注意,在上面的代碼中,雖然將方法返回的數組賦值給局部變量(此處為some_other_array
),但您不必使用[]
括號。
並且不要初始化some_other_array
變量,只需進行聲明,以便在為其分配方法返回的數組時,它將自動具有返回數組的大小。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.