Varargs method parameter
| Code | static void main() {
printInfo("Winner", 34);
}
public static void printInfo(final String msg, final int value) {
IO.println(msg + ": " + value);
} |
|---|---|
| Result | "Winner": 34 |
| Code | printInfo("Winner", 34); // One int value printInfo("Winner", 31, 7); // Two int values printInfo("Winner", 2, 8, 5); // Three int values ----------------------------------------------------------------------------- public static void printInfo(String msg, int value) { ...} public static void printInfo(String msg, int value1, int value2) { IO.println(msg + ": " + value1 + " " + value2 ); } public static void printInfo(String msg, , int value1, int value2, int value3) { IO.println(msg + ": " + value1 + " " + value2 + " " + value3); } |
|---|---|
| Result | Winner: 34 Winner: 31 7 Winner: 2 8 5 |
-
Similar code in multiply overloaded methods.
-
Tedious: Each added argument requires adding another method.
Objective: Get rid of boilerplate code!
| Code | printInfo("Winner", new int[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9}); ------------------------------------------------------------- public static void printInfo(String msg, int[] values) { IO.print(msg + ": " ); for (int v: values) { IO.print(v + " "); } IO.println(); } |
|---|---|
| Result | Winner: 1 2 3 4 5 6 7 8 9 |
-
Clumsy, requires
printInfo("Winner", new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 });rather than
printInfo("Winner", { 1, 2, 3, 4, 5, 6, 7, 8, 9 }); // Syntax error
Objective: Simplify parameter passing
| Code | final int[] values = { 1, 2, 3, 4, 5, 6, 7, 8, 9}; printInfo("Winner", values); // Array of int printInfo("Winner", 20, 19, 18, 17, 16, 15); // Separate values --------------------------------------------------------------- public static void printInfo(String msg, int ... values) { IO.print(msg + ": " ); for (int v: values) { IO.print(v + " "); } IO.println(); } |
|---|---|
| Result | Winner: 1 2 3 4 5 6 7 8 9 Winner: 20 19 18 17 16 15 |
-
Replace
printInfo(String msg, int[] values) -
By
printInfo(String msg, int ... values)
-
Only one varargs parameter per method.
-
Must be the method's last argument.
No. 147
Creating a flexible max(...) method.
|
Q: |
Get inspired by
|
||||
|
A: |
The varargs mechanism allows for defining: |
No. 148
Enforcing mandatory arguments
|
Q: |
As being stated in the
Unfortunately this error does not show up until run-time and thus represents a hidden flaw. Tasks:
|
||||
|
A: |
Now at least one argument is being required. Violation yields a compile-time rather than just a run-time error:
|
