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?
Any reference type varargs argument can be assigned to an
Object
array. In your particular case, each element of theObject
array will be aList<String>
.Your code would be more clear (and type safe) if you changed the type of the array though :
This shows that you are not converting a
List
to an array. You just assign zero, one or multipleList
s to an array ofList
s.