可変長引数
可変長引数について。
- メソッドの引数の型の末尾に「...」を付けると可変長引数を受け付けるメソッドができます。
- 可変長にできる引数は、一番最後の引数1つのみです。
- メソッド内部では、可変長引数に配列としてアクセスできます。
/** * 可変長引数を受け付けるメソッド * * @param strs 引数 */ static void test( String... strs ) { // メソッド内では配列としてアクセスする。 System.out.println( strs.length ); for ( String str : strs ) { System.out.println( str ); } }
サンプル。
test( "a", "b", "c" ); System.out.println( "---" ); // 引数なしやnullもOK test(); System.out.println( "---" ); test( null, "x", null ); System.out.println( "---" ); // 内部的には配列なのでこんな呼び出しも可能。 test( new String[] { "a", "b" } );
実行結果です。
3 a b c --- 0 --- 3 null x null --- 2 a b