arguments. This feature is also known as "var-args", "varargs", "variable-length argument lists" or "variable arguments,".
Var-args declarations
Here are some legal and illegal var-arg declarations:
Legal:
void myMethodX( int... a ) { } // expects from 0 to many ints // as parameters void myMethodY( char c, int... a ) { } // expects first a char, // then 0 to many ints void myMethodZ( Animal... animal ) { } // 0 to many Animals void myMethodXYZ( Object... anyKindOfObjects ) { } // 0 to many Objects
Illegal:
void myMethodA( int x... ) { } // illegal syntax void myMethodB( String... str, byte b ) { } // var-arg must be last void myMethodC( int... x, char... y ) { } // too many var-args
Accessing var-args
Example 1:
public static void test(int some, String... args) {
System.out.print("\n" + some);
for(String arg: args) {
System.out.print(", " + arg);
}
}
Example 2:
static int sum (int ... numbers)
{
int total = 0;
for (int i = 0; i < numbers.length; i++)
total += numbers [i];
return total;
}
No comments:
Post a Comment