2012-02-28 17 views
1

私は方法のStringのvarargsに、一つのパラメータを持つ2つのメソッドをオーバーロードしたいと別のString[]が、私は次のコンパイル時エラー達成:過負荷の二つの方法のString []パラメータ

Duplicate method registerByName(String...) 

私のスニペットコードを次のとおりです。

public void registerByName(String[] names) 
{ 

} 

public void registerByName(String...names) 
{ 

} 

なぜですか?

答えて

1

varargは、(Object[])を配置する別の方法です。したがって、MyMethod(MyObject[] obj)MyMethod(MyObject... obj)のメソッドはコンパイラと同じです。それはただ構文的な砂糖です。

あなたは

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

ようなメソッドを持っている場合は、配列引数でそれを呼び出すことは完全に合法である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. [...]

0

を参照できます:このため

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

理由は、Type[]とでオーバーロードできません。

JVMは、これら2つのシグネチャの違いを知りません。 varargsメソッドを使用してクラスファイルにjavapを実行してみてください。

+0

これは良い説明であるかどうかわかりません。 'int'引数を使って' foo(Integer x) 'を呼び出すこともできますが、両方のバリエーションでメソッドに依然として過負荷がかかるので、この推論は必ずしも機能しません。 (答えの最後の文はそれに似ています)。 – Thilo

+0

@ティヒョ・フェア・ポイント。 –

2

"文字列..."と "文字列[]"はまったく同じものです...