簡體   English   中英

如何在Java中創建數組參數?

[英]How do I make an array parameter in java?

我試圖為方法的數組創建一個參數,但是它總是會出錯。

public void methodExample1() {
int array1[] = new int[4]
}

public void methodExample(Array array1[]) {

System.out.println(array1[0]);
}

但是它總是說我的參數有錯誤。 有什么辦法嗎?

嘗試這個:

public void methodExample(int[] array1)

說明:類型與您用於聲明將作為參數傳遞的值(目前我忽略協變量數組)的類型相同,例如,如果執行此操作:

int[] array1 = new int[4];

...然后,在將其作為參數傳遞時,我們將其編寫為:

methodExample(array1)

還要注意,數組的大小一定不能作為參數傳遞,按照約定, []部分在數組元素的類型之后(實際上, int[] 數組的類型)之后,而不是數組的名稱。

我假設您正在嘗試將數組作為參數傳遞給方法,以對其進行初始化,然后調用另一個方法進行打印?

在Java中,您必須創建一個對象並通過調用new對象為其“分配”內存空間。

所以你可以這樣:

public static void main(String[] args) {

        int [] m_array; // creating a array reference 
        m_array = new int[5]; // allocate "memory" for each of of them or you can consider it as creating a primitive of int in each cell of the array

        method(m_array); // passing by value to the method a reference for the array inside the method
        }
        public void method(int [] arr)  // here you are passing a reference by value for the allocated array
        {
            System.out.println(arr[0]);
        }

如果我理解您的問題,則可以使用Array ,例如

public static void methodExample(Object array1) {
    int len = Array.getLength(array1);
    for (int i = 0; i < len; i++) {
        System.out.printf("array1[%d] = %d%n", i, Array.get(array1, i));
    }
}

public static void main(String[] args) {
    methodExample(new int[] { 1, 2, 3 });
}

輸出是

array1[0] = 1
array1[1] = 2
array1[2] = 3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM