Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you return a dereferenced array?

I wish to do the something like the following:

public static int[] plusOneLengthFour(int[] arr) {
  return {arr[0]+1,arr[1]+1,arr[2]+1,arr[3]+1};
}

But at compile time, I get the following error:

TestClass.java:5: error: illegal start of expression
        return {arr[0]+1,arr[1]+1,arr[2]+1,arr[3]+1};

What's wrong here?

like image 904
golddove Avatar asked Aug 02 '26 21:08

golddove


1 Answers

You just need to add new int[] to your return statement to compile it. It doesn't know what you want if you just start with curly braces. Note that this will return a new array, while the original arr will have the same values.

i.e.,

return new int[] {arr[0]+1,arr[1]+1,arr[2]+1,arr[3]+1};
like image 173
asteri Avatar answered Aug 04 '26 12:08

asteri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!