public class VarargsParamVsLocalVariable {
static void f(List<String>... stringLists) {
// compiles fine! No problems in Runtime as well.
Object[] array = stringLists;
}
//but the same fails if List<String> is not a vararg parameter
public static void main(String[] args) {
List<String> stringLists;
List<String> stringLists1 = new ArrayList<>();
//below lines give: "cannot convert from List<String> to Object[]"
Object[] array = stringLists; // compile error!
Object[] array1 = stringLists1; // compile error!
}
}
// Why I can assign List<String> variable to Object[] variable if List<String> variable is a vararg parameter?
Why I can assign List variable to Object[] variable if List variable is a vararg parameter?
Because a Varargs like List<String>... stringLists
is somehow equivalent to an array like List<String>[] stringLists
.
To make your code compile you should create an array
as next:
Object[] array1 = {stringLists1};
For stringLists
, you will need to initialize it first otherwise even if you try to create an array as above it won't compile.
For the same reason public static void main(String[] args) {
could be rewritten:
public static void main(String... args) {
Because Java didn't originally have varargs. They way they were added is by treating that varargs parameter as though it were an array.
Effectively, this
static void f(List<String>... stringLists)
...is the same as
static void f(List<String>[] stringLists)
...and so it's assignment-compatible with Object[]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With