How to set values for an array attribute?

Asked

Viewed 901 times

1

I have a java class representing an entity snack,follows below the class:

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

Below follows the test class in which I am 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 correctly set the ingredients attribute, which is an array of strings? Because as I exemplified this giving the following error:

The method setIngredientes(String[]) in the type Lanche is not applicable for the Arguments (String, String, String)

1 answer

3


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

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

Or it can be done also 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 the arguments in the same way:

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

The variable ingredientes remains an array, as can be seen in this test on ideone: https://ideone.com/4mBvs6

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

Browser other questions tagged

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