Varargs Methods Bridge To Arrays
A varargs parameter compiles to an array argument: callers pass loose arguments, and an existing array slots in directly as the last parameter.
Code
import java.util.Arrays;
public class VarargsBridge {
// int... 编译后就是 int[] 形参;调用方按变长实参书写
static int sum(int... values) {
int total = 0;
for (int v : values) {
total += v;
}
return total;
}
static String join(String separator, Object... parts) {
String[] texts = Arrays.stream(parts).map(String::valueOf).toArray(String[]::new);
return String.join(separator, texts);
}
public static void main(String[] args) {
System.out.println("sum() = " + sum());
System.out.println("sum(1, 2, 3) = " + sum(1, 2, 3));
int[] bundled = {4, 5, 6};
System.out.println("sum(array) = " + sum(bundled)); // 数组直接传入 varargs
System.out.println(join(" | ", "a", 2, true));
}
}What this snippet does
Varargs Methods Bridge To Arrays keeps everything in the class VarargsBridge and the functions sum, join and main.
The loop for (int v : values) is the only repeated construct.
Caveats
- No lockfile entry, no version pinning — the file needs nothing beyond the runtime.
Applying it
The principal signature, verbatim: static int sum(int... values)
The demo output is labeled (sum() =, sum(1, 2, 3) =, sum(array) =), which keeps every printed line tied to the operation that emitted it.
The entry point wires sum and join together — run it once and the whole demo flows.
Statements that matter
String[] texts = Arrays.stream(parts).map(String::valueOf).toArray(String[]::new);
return String.join(separator, texts);
Interactive Tools for This Topic
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- What does Varargs Methods Bridge To Arrays print when run?
- Execute the whole file; each printed line is prefixed with a label like `sum() =`, `sum(1, 2, 3) =`, `sum(array) =`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.