[英]pass an array object in a parameter
我是java新手,我想知道,我們如何將數組對象作為參數傳遞給方法。讓我們說如果我有:
public void sortArray(A[7])
我應該在括號之間放什么? 應該是A[length of array]
還是什么?
將數組作為參數傳遞時,其長度以及存儲在其中的內容將被傳遞,因此您無需專門指定長度。 有關實現,請參閱以下示例:
將int數組作為參數的方法的簡單示例:
public void takeArray(int[] myArray) {
for (int i = 0; i < myArray.length; i++) { // shows that the length can be extracted from the passed in array.
// do stuff
}
}
你可以這樣調用這個方法:
假設你有一個像這樣的數組:
int[] someArray = {1, 2, 3, 4, 5};
然后用以下方法調用上面的方法:
takeArray(someArray);
只需將數組傳遞給方法即可。 你不需要提及任何尺寸。
void sortArray(int[] array) {
// Code
}
//調用方法並傳遞此數組。
int[] array = new int[10];
sortArray(array);
例如,你有如你所說的程序:
public void sortArray(typeArray[] A){
//code
//code
}
調用數組:
typeArray[] A = new typeArray[N]; //N is number of array you want to create
searchArray(A); //this how I call array
您只需將數組的名稱傳遞給方法。
int[] a = new int[10];
...
bar(a);
其中bar定義如下:
void bar(int[] a)
{
...
}
這樣您就可以傳遞數組
int[] a = new int[100];
myFunction(a);
public void myFunction(int[] a){
for(int i =0; i< a.lenght();i++){
System.out.println(i);
}
}
如果您不希望將數組命名為:還可以創建匿名數組:
public void array(int arr[])
{
// code handling arr
}
現在,對於上面的方法,您可以傳遞一個數組對象而不創建它:
public static void main(String[] args)
{
array(int[] {1,2,3,4,5});
}
這也稱為未命名數組或匿名數組。 無需為按值調用創建數組。 如果您不再需要main()方法中的該數組,則可以使用未命名的數組。 這有助於節省內存。 謝謝
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.