lst; Object [] o = lst;" if List is varargs? public class VarargsParamVsLocalVariable { static voi...">

Why does it compile "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 can I assign the List variable to the Object [] variable if the List variable is a vararg parameter?

+4
source share
6 answers

Since Varargs is List<String>... stringListssomehow equivalent to an arrayfor example List<String>[] stringLists.

To compile your code, you must create arrayas follows:

Object[] array1 = {stringLists1};

For stringListsyou will need to initialize it first, otherwise even if you try to create an array as described above, it will not compile.

public static void main(String[] args) { :

public static void main(String... args) {
+4

Java varargs. varargs, .

,

static void f(List<String>... stringLists)

...

static void f(List<String>[] stringLists)

... Object[].

+3

varargs Object. Object List<String>.

( ), :

static void f(List<String>... stringLists) {
    List<String>[] array = stringLists; 
}

, List . , List List s.

+1

:

static void f(List<String>... stringLists) {
    // compiles fine! No problems in Runtime as well.
    Object[] array = stringLists; 
}

stringLists - List<String> (List<String>[]), - .

, , List<String> . ( []) . , , -... , .

0

varargs - , vararg ().

, varargs f stringLists - vararg, (List<String>[]) Object[]

0

Varargs . , .

, Varargs - , , Explicity.

, List<String> ... varargs List<String>[] generics, : -

   Parent[] par = new child[];
   Object[] objArray = new xyz[];

: -       [] o = lst = List<String>[]= List<String> ...

javadocs

-1

Source: https://habr.com/ru/post/1663930/


All Articles