I understand that if you want to return something that's stored in a variable, it's as simple as returning said variable:
int jellyfish = 7;
return jellyfish;
and if you just wanted to return the number seven without any relation to jellyfish, you could just write:
return 7;
But how would this be possible for arrays? Up to this point, I declare the array that I want to return the values of and then just return that array directly in the next line, but it feels just as klunky as making the variable "jellyfish" above the return line for when the code nly ever intended to return 7. Like I would code:
public int[] make2(int[] a, int[] b) {
int[] result = new int[2];
if (a.length >= 2) {
result[0] = a[0];
result[1] = a[0];
return result;
}
return b;
}
Even though it feels as though it'd be much simpler to just write something like:
public int[] make2(int[] a, int[] b) {
int[] result = new int[2];
if (a.length >= 2) {
return {a[0], a[1]}; // <--- changed line
}
return b;
}
I'm sure something like that exists, but nothing that I've tested as of yet will let me return array information without putting it in a new array variable before the return statement. Is there a way to do this that I'm not aware of or is this an inherent problem within Java that I can't do anything about?
CodePudding user response:
You can try like this.
public int[] make2(int[] a, int[] b) {
if (a.length >= 2) {
return new int[]{a[0], a[1]}; // <--- changed line
}
return b;
}
CodePudding user response:
Let's make this step by step. You know how you create a new integer array, since you did it in your snippet here
int[] result = new int[2];
Then you have to know, there is a thing called the Array Initializer, which lets you initialize the array values at creation. For example:
int[] result = new int[]{ 1, 2, 3 };
So, the solution to your question would be (combining this knowledge) the following:
return new int[]{ a[0], a[1] };
which creates and returns a new integer array of size 2, containing the values of a[0]
and a[1]
.