這是我的2維數組:採用2維對象數組
String[][] theMaze = new String[row][column];
如何在這個方法中使用它?
public void ruteToX(String[][] theMaze){
// call theMaze and process in this method
}
這是我的2維數組:採用2維對象數組
String[][] theMaze = new String[row][column];
如何在這個方法中使用它?
public void ruteToX(String[][] theMaze){
// call theMaze and process in this method
}
假設我理解你的問題是正確的。
我會告訴你一個將數組傳遞給方法ruteToX(...)
的示例。
public class Example
{
String[][] theMaze = new String[5][5];
public void ruteToX(String[][] theMaze)
{
//call theMaze and process in this method
}
public static void main(....)
{
Example ob=new Example();
ob.ruteToX(ob.theMaze);
//passed the value of reference or the pointer to the function ruteToX(...)
}
}
它是如何通過的?
當你傳遞一個數組時,它在內存中的值是pointer or reference
,這意味着如果你對方法中的參數數組做了任何改變,實際的數組也將面對相同的改變(因爲它們是相同的 - 同名參考)。
當陣列中的傳遞,在以前的方法調用的方法和傳遞數組中僅使用變量名稱(「之前ruteToX」無論正在運行)。
public void previousMethod(){
ruteToX(theMaze);
}
public void ruteToX(String[][] theMaze){
// call theMaze and process in this method
}
編輯: 另外,一旦在該方法既可以使用陣列原樣或創建一個新的數組等於原始陣列。
public void ruteToX(String[][] theMaze){
String[][] secondMaze = theMaze;
}
我不同意'創建一個等於原始數組的新數組'。 –
@MathewsMathai同意這不是一個很好的例子,但我想提供多個選項。 – AnthonyGordon
這不是關於決定。 'String [] [] secondMaze = theMaze;'不創建新數組。由於您正在使用'=',因此您創建的新數組對象具有相同的引用。 –
什麼應該在裏面? –
你打算將數組傳遞給該方法嗎? –
是的,先生。馬修。這是數組充滿主要價值。而不是如何調用已經填充方法ruteToX的數組? – Wisnu