Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store an array returned by a method in Java

I want to store the array returned by a method into another array. How can I do this?

public int[] method(){
    int z[] = {1,2,3,5};
    return z;
}

When I call this method, how can I store the returned array (z) into another array?

like image 640
Mohammad Sepahvand Avatar asked Mar 04 '10 11:03

Mohammad Sepahvand


People also ask

Can you return an array from a method Java?

We can return an array in Java from a method in Java. Here we have a method createArray() from which we create an array dynamically by taking values from the user and return the created array.

Can you store methods in an array Java?

An array is a data structure used to store data of the same type. Arrays store their elements in contiguous memory locations. In Java, arrays are objects. All methods of class object may be invoked in an array.

How do you call an array from a method in Java?

To pass an array to a function, just pass the array as function's parameter (as normal variables), and when we pass an array to a function as an argument, in actual the address of the array in the memory is passed, which is the reference.

Can arrays be returned from a function?

C programming does not allow to return an entire array as an argument to a function. However, you can return a pointer to an array by specifying the array's name without an index.


2 Answers

public int[] method() {
    int z[] = {1,2,3,5};
    return z;
}

The above method does not return an array par se, instead it returns a reference to the array. In the calling function you can collect this return value in another reference like:

int []copy = method();

After this copy will also refer to the same array that z was refering to before.

If this is not what you want and you want to create a copy of the array you can create a copy using System.arraycopy.

like image 179
codaddict Avatar answered Oct 11 '22 12:10

codaddict


int[] x = method();
like image 28
saugata Avatar answered Oct 11 '22 12:10

saugata