Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a temporary int array in Java [duplicate]

How can I manage to return a temporary array in Java (in order to save code line, without creating a variable).

When doing initiation, I can use

int[] ret = {0,1};

While when doing return, I cannot use

return {0,1};

Do I miss something or is there a force typ-cast to do this?

I got the idea to use new int[] as the answers below. While, what's the reason the we don't need new int[] when doing initiation?

like image 232
newbieSOF Avatar asked Feb 29 '16 15:02

newbieSOF


4 Answers

I got the idea to use new int[] as the answers below. While, what's the reason the we don't need new int[] when doing initiation?

When you write int[] ret = {0,1};, it is essentially a shortcut of writing int[] ret = new int[]{0,1};. From the doc:

Alternatively, you can use the shortcut syntax to create and initialize an array:

int[] anArray = { 
    100, 200, 300,
    400, 500, 600, 
    700, 800, 900, 1000
};

Now when you return you have to explicitly write return new int[]{0,1}; because you are not doing an assignment operation(create and initialize as per the doc) to the array and hence you cannot use the shortcut. You will have to create an object using new.

like image 56
Atri Avatar answered Oct 31 '22 12:10

Atri


You can do something known as returning an anonymous array (as it has no name).

Do

return new int[] {0, 1};

for that...

like image 33
ΦXocę 웃 Пepeúpa ツ Avatar answered Oct 31 '22 10:10

ΦXocę 웃 Пepeúpa ツ


   public int [] return check(){
       return new int[] {5,8,3,6,4};
     }
like image 6
Vikrant Kashyap Avatar answered Oct 31 '22 10:10

Vikrant Kashyap


You can do something likewise,

return new int[]{1,2,3};
like image 4
Vishal Gajera Avatar answered Oct 31 '22 11:10

Vishal Gajera