Passing multiple parameters as an Array

Asked

Viewed 233 times

4

I have a method that takes an unknown amount of parameters like an Array, thus:

public void enviarCampos(String funcao, String... campos) {
  // Ação do método
}

To call this method do:

enviarCampos("CADASTRAR", "nome", "dataNascimento", "sexo", "rg", "cpf");

The problem is that I don’t know what these parameters will be, they will depend on various conditions, so I can’t put fixed. I put these parameters in a ArrayList, so that I can manipulate the list of parameters, and I tried to make a cast to call the method but it did not work:

ArrayList<String> listaCampos = new ArrayList<>(Arrays.asList("nome", "dataNascimento", "sexo", "rg", "cpf"));
enviarCampos("CADASTRAR", (String[]) listaCampos.toArray());

Someone knows how to do?

1 answer

3


Use the method toArray(T[] arr):

ArrayList<String> listaCampos = new ArrayList<>(Arrays.asList("nome", "dataNascimento", "sexo", "rg", "cpf"));
enviarCampos("CADASTRAR", listaCampos.toArray(new String[listaCampos.size()]));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.