user1232256
user1232256

Reputation:

overload two methods with vararg and String[] parameter

I want overload two method with one parameter, in a method varargs of String and another String[] but I achieve following compilation-time error:

Duplicate method registerByName(String...)

My snippet code is:

public void registerByName(String[] names)
{

}

public void registerByName(String...names)
{

}

Why?

Upvotes: 2

Views: 478

Answers (3)

Nishant
Nishant

Reputation: 55866

vararg is another way to place (Object[]) so a Method MyMethod(MyObject[] obj) and MyMethod(MyObject... obj) are the same to compiler. It's just syntactic sugar.

You could refer the doc

It is still true that multiple arguments must be passed in an array, but the varargs feature automates and hides the process. Furthermore, it is upward compatible with preexisting APIs. So, for example, the MessageFormat.format method now has this declaration:

public static String format(String pattern,
                            Object... arguments);

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

Upvotes: 1

plucury
plucury

Reputation: 1120

"String..." and "String[]" are exactly one thing...

Upvotes: 2

Daniel Lubarov
Daniel Lubarov

Reputation: 7924

If you have a method like

public static void registerByName(String... names);

It is perfectly legal to call it with an array argument:

registerByName(new String[] {"sam"});

For this reason, you can't overload with Type[] and Type....

The JVM doesn't even know the difference between these two signatures. Try running javap on a class file with a varargs method.

Upvotes: 0

Related Questions