2

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?

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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.

1 Comment

I don't know if that is a good explanation. You can call a foo(Integer x) with an int argument, too, but still overload the method in both variations, so this reasoning does not always work. (The last sentence of the answer is more like it).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.