How can I make a constructor that contains a number of the same objects but if one its empty to ignore it?

RafaelKoll :

I want to make a constructor for a wrap that contains four fillings, but if one filling is empty (for example only 2 or 3 used instead of 4) to execute the code without any problem.

I currently can only include only one filling with this code.

Wrap one=new Wrap( new Bread("Italian"), new Filling("Ham"),new Topping("Cheddar"));
cricket_007 :

With your current constructor, you can only have zero (null) or one bread, filling and topping.

You'll want to overload your constructor to allow for more input options.

If you want to have more than one filling and at most one topping, add this constructor

Wrap(Bread b, List<Filling> fillings, Topping topping)

If you want to have more than one filling and topping, then this

Wrap(Bread b, List<Filling> fillings, List<Topping> toppings)

Or just allow for the last case, and use Collections.singletonList() for lists of one item.


And you can combine them using this().

Summing up, this is an example

Bread bread;
List<Filling> fillings;
List<Topping> toppings;

public Wrap(Bread b, List<Filling> fillings, List<Topping> toppings) {
    // ...
}

public Wrap(Bread b, Filling f, Topping t) {
    this(b, Collections.singletonList(f), Collections.singletonList(t));
}

public Wrap(Bread b, List<Topping> toppings) {
    // Is this a pizza?
    this(b, null, toppings);
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=102834&siteId=1