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?
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
.
You can do something known as returning an anonymous array (as it has no name).
Do
return new int[] {0, 1};
for that...
public int [] return check(){
return new int[] {5,8,3,6,4};
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With