Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are these methods ambiguous? (one takes array, another takes varargs)

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?

like image 609
Dims Avatar asked Jul 03 '15 07:07

Dims


People also ask

Can you pass array to 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.

How does Varargs work in Java?

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[].

What is the difference between Varargs and array in Java?

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.


2 Answers

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.

like image 77
inquisitive Avatar answered Oct 17 '22 22:10

inquisitive


They have the same definition.

In fact, int ... array2 is equivalent to int[] array2.

like image 7
Burkhard Avatar answered Oct 17 '22 22:10

Burkhard