How to set values of an array attribute?

1

I have a java class that represents a snack , below the class:

public class Lanche {
    private String nome;
    private int id;
    private double preco;
    private String[] ingredientes;
/*getters setters */
}

Below is the test class in which I'm instantiating a snack object and setting the attributes:

public class Teste {
    public static void main(String[] args) {

        Lanche lanche = new Lanche();
        lanche.setId(001);
        lanche.setNome("X-salada");
        lanche.setPreco(5.00);
        lanche.setIngredientes("Hamburguer","Queijo","Salada");
    }
}

How to properly set the ingredients attribute, what is an array of strings? Because of the way I have exemplified this it gives the following error:

  

The method setIngredients (String []) in the type Snack is not applicable for the arguments (String, String, String)

    
asked by anonymous 18.03.2018 / 18:48

1 answer

4

By error, the method expects an array of strings and not 3 strings separated as a parameter. There are several ways to fix but I believe the below is the least drastic:

lanche.setIngredientes(new String[]{"Hamburguer","Queijo","Salada"});

Or it can also be done using varargs , where you must change the signature of your method as below:

public void setIngredientes(String... ingredientes){
    //... codigo do método
}

and continue passing arguments in the same way:

lanche.setIngredientes("Hamburguer","Queijo","Salada");

The variable ingredientes remains an array, as can be seen in this test in the ideone: link

To learn more about varargs , see the links below, taken right here from the site:

18.03.2018 / 18:52