How are these append()
methods ambiguous?
public class Try_MultipleArguments {
public static void main(String[] args) {
int array1[] = new int[] {1, 2, 3};
int array2[] = new int[] {4, 5, 6};
append(array1, array2);
append(array1, 4, 5, 6);
}
public static int[] append(int[] array1, int[] array2) {
int[] ans = new int[array1.length + array2.length];
for(int i=0; i<array1.length; ++i) {
ans[i] = array1[i];
}
for(int i=0; i<array2.length; ++i) {
ans[i+array1.length] = array2[i];
}
return ans;
}
public static int[] append(int[] array1, int ... array2) {
return append(array1,array2);
}
}
UPDATE
Varargs is equivalent to an array, but this is from inside of the method. From outside of the method it should not be equivalent to it.
UPDATE 2
I see now that I can pass an array to vararg. I didn't knew that. Was always workarounding this need. Hmmm.... Was this from the very beginning of java varargs?
If you're passing an array to varargs, and you want its elements to be recognized as individual arguments, and you also need to add an extra argument, then you have no choice but to create another array that accommodates the extra element.
Syntax of Varargs Hence, in the Varargs method, we can differentiate arguments by using Index. A variable-length argument is specified by three periods or dots(…). This syntax tells the compiler that fun( ) can be called with zero or more arguments. As a result, here, a is implicitly declared as an array of type int[].
Arrays and varargs are two completely different things. The only relationship is that varargs is implemented using arrays. Talking about the "difference between arrays and varargs" is like talking about the difference between between sugar and cake.
From the docs:
The three periods after the final parameter's type indicate that the final argument may be passed as an array or as a sequence of arguments.
So it's ambiguous because array also maps to the varargs.
They have the same definition.
In fact, int ... array2
is equivalent to int[] array2
.
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