Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why it compiles "List<String> lst; Object[] o = lst;" if List<String> is varargs?

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?

like image 802
LrnBoy Avatar asked Mar 10 '23 09:03

LrnBoy


2 Answers

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) {
like image 54
Nicolas Filotto Avatar answered Apr 30 '23 09:04

Nicolas Filotto


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[].

like image 34
T.J. Crowder Avatar answered Apr 30 '23 08:04

T.J. Crowder