Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are String [] and String... (Var-args) same when they work internally?

class WrongOverloading{
    void something(String [] a){ .. }
    Integer something(String... aaa){ return 1;}
}

Above code does not compile! Compiler says these are duplicate methods. So using String array or String var-args exactly mean the same?

How are they implemented internally?

like image 708
whitehat Avatar asked Jan 06 '12 07:01

whitehat


2 Answers

They are effectively the same, except the compiler will not accept an varargs unless its the last argument and it won't allow you to pass multiple arguments to an array.

public void methodA(int... ints, int a); // doesn't compile
public void methodA(int[] ints, int a); // compiles

public void methodB(int... ints); // compiles
public void methodC(int[] ints); // compiles

methodB(1); // compiles
methodB(1,2,3,4); // compiles
methodC(1); // doesn't compile
methodC(1,2,3,4); // doesn't compile
like image 52
Peter Lawrey Avatar answered Nov 15 '22 13:11

Peter Lawrey


From this SO discussion

The underlying type of a variadic method function(Object... args) is function(Object[] args). Sun added varargs in this manner to preserve backwards compatibility.

So, as every other answer has said, yes, they're the same.

like image 34
blahman Avatar answered Nov 15 '22 12:11

blahman