简体   繁体   中英

How do I make an array parameter in java?

I tried to make a parameter for an array for a method, but it always comes up with an error.

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

public void methodExample(Array array1[]) {

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

But it always says there's an error in my parameter. Is there any way to do this?

Try this:

public void methodExample(int[] array1)

Explanation: The type is the same that you used for declaring a value that will be passed as parameter (for the moment I'm ignoring covariant arrays), for instance if you do this:

int[] array1 = new int[4];

... Then, at the time of passing it as a parameter we'll write it like this:

methodExample(array1)

Also notice that the size of the array must not be passed as parameter, and that by convention the [] part goes right after the type of the array's elements (in fact, int[] is the type of the array), and not after the array's name.

I assume that you are trying to pass array as a parameter to a method , to initialize it and then call another method to print it?

In java you have to create an object and "allocate" memory space for it by calling to new ...

so you can do like that :

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]);
        }

If I understand your question, then you could use Array , and something like

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 });
}

Output is

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM