library
intermediateVarargs & SafeVarargs
Use variable-length arguments safely and understand heap pollution warnings with generic varargs.
Varargs (Java 5) lets a method accept zero or more arguments of the same type. The compiler creates an array behind the scenes.
Varargs = a gift bag at a store. Whether the customer gives you 1 item, 5 items, or 0 items, you put them all in the same bag (array). The store doesn't need different checkout lines for different quantities.
Key Concepts
1
Syntax: void log(String... messages) — messages is a String[]
2
Rules:
- Only one varargs parameter per method
- Must be the last parameter
- Caller can pass individual values, an array, or nothing
3
Generic varargs: List<String>... is problematic because of type erasure. The runtime array is List[] (raw), which can hold any List — this is 'heap pollution'.
4
@SafeVarargs: suppresses the 'unchecked' warning on generic varargs. Only use when you're certain the method doesn't:
- Store anything in the varargs array
- Expose the array to untrusted code
5
Can be applied to: final methods, static methods, private methods, and constructors.
6
Common JDK varargs: Arrays.asList(T...), Collections.addAll(Collection, T...), List.of(E...), String.format(String, Object...).