I want to store all the variables values passed in constructor to ArrayList declared in the same class. Please look at the code below:
This is the "Additions" class:
public class Additions {
private ArrayList<Boolean> additions;
private boolean salad;
private boolean tomato;
private boolean cucumber;
private boolean onion;
public Additions(boolean salad, boolean tomato, boolean cucumber, boolean onion) {
this.salad = salad;
this.tomato = tomato;
this.cucumber = cucumber;
this.onion = onion;
}
}
And this is the main class, where I’m declaring my object:
public class Main {
public static void main(String[] args) {
Additions additions = new Additions(true, true, true, true);
}
}
Okay, as I mentioned. My problem is to store all values passed in the constructor above, to this class’s field named additions.
The reason I want to do this, is display declared values (eg. [true, true, true, true]) in console.
Thanks for your help in advance!
>Solution :
First solution is you can easily add them to the ArrayList and override toString
public class Additions {
private ArrayList<Boolean> additions;
private boolean salad;
private boolean tomato;
private boolean cucumber;
private boolean onion;
public Additions(boolean salad, boolean tomato, boolean cucumber, boolean onion) {
this.salad = salad;
this.tomato = tomato;
this.cucumber = cucumber;
this.onion = onion;
this.additions = new ArrayList<>();
additions.add(salad);
additions.add(tomato);
additions.add(cucumber);
additions.add(onion);
}
@Override
public String toString() {
return additions.toString();
}
}
Another solution is to replace your boolean variables with a single map so you can add or remove any number of attributes easily without changing the number of variables, any you can check by name if this attributes is enabled or not and also override to string
public class AdditionsMap {
private Map<String, Boolean> attributesMap;
public AdditionsMap(boolean salad, boolean tomato, boolean cucumber, boolean onion) {
attributesMap = new HashMap<>();
attributesMap.put("salad", salad);
attributesMap.put("tomato", tomato);
attributesMap.put("cucumber", cucumber);
attributesMap.put("onion", onion);
}
public boolean isAttributeEnable(String name) {
return attributesMap.getOrDefault(name, false);
}
@Override
public String toString() {
return attributesMap.toString();
}
}
public static void main(String... args) {
Additions additions = new Additions(true, true, true, true);
System.out.println(additions);
AdditionsMap additionsMap = new AdditionsMap(true, true, true, true);
System.out.println(additionsMap);
}
Output will be like
[true, true, true, true]
{salad=true, cucumber=true, onion=true, tomato=true}