Assumere un metodo con la seguente firma:Come posso passare un ArrayList ad un metodo che prevede un vararg (Object ...)?
public static void foo(String arg1, String args2, Object... moreArgs);
Quando si esegue ...
ClassName.foo("something", "something", "first", "second", "third");
... Prendo moreArgs[0] == "first"
, moreArgs[1] == "second"
e moreArgs[2] == "third"
.
Ma supponiamo di avere i parametri memorizzati in un ArrayList<String>
chiamato arrayList
che contiene "prima", "seconda" e "terza".
voglio chiamare foo
modo che moreArgs[0] == "first"
, moreArgs[1] == "second"
e moreArgs[2] == "third"
utilizzando il arrayList
come parametro.
Il mio tentativo ingenuo era ...
ClassName.foo("something", "something", arrayList);
... ma che mi darà moreArgs[0] == arrayList
che non è quello che volevo.
Qual è il modo corretto per passare arrayList
al metodo foo
sopra in modo che moreArgs[0] == "first"
, moreArgs[1] == "second"
e moreArgs[2] == "third"
?
Si prega di notare che il numero di argomenti in arrayList
sembra essere tre in questo caso specifico, ma la soluzione che sto cercando dovrebbe ovviamente essere generale e funzionare per qualsiasi numero di argomenti in arrayList
.
Oh, era così semplice! Pensavo Object ...! = Object []. Grazie! :-) – knorv
In generale Object! = Object [], ma per i metodi varargs, il compilatore converte un parametro MyType ... in un parametro MyType [] e avvolge tutti gli argomenti in un array in fase di runtime che viene passato alla funzione. Quindi, in questo caso, puoi sfruttare la firma interna segreta del metodo varargs passando in modo esplicito un riferimento di matrice. –