Nilesh Kumar Nilesh Kumar - 1 month ago 9
Java Question

Add objects in ArrayList while designing class in Java

I'm trying to create Patient and Allergy class and I'm confused about List allergies in setAllergies, whether it should be:

this.allergies = allergies;


or

allergies.add(allergies);


Patient class:

public class Patient {

private List<Allergy> allergies;

public List<Allergy> getAllergies() {
return allergies;
}

public void setAllergies(List<Allergy> allergies) {
this.allergies = allergies;
}

}


Allergy class:

public class Allergy {
private String name;
private Severity severity;

public Allergy(String name, Severity severity) {
this.name = name;
this.severity = severity;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Severity getSeverity() {
return severity;
}

public void setSeverity(Severity severity) {
this.severity = severity;
}
}

Answer Source
allergies.add(allergies);

adds a object to itself.
Why doing that ? Besides you cannot add a List to a List with add().
You have to use addAll() for that.


Actually the allergies field is null when a Patient instance is created.

As a consequence, doing it : allergies.invokeSomething(...); will throw a NullPointerException. Besides, the "set" prefix has a semantics to overwrite/replace, not to add.
So you should keep your method as you wrote for the moment :

public void setAllergies(List<Allergy> allergies) {
    this.allergies = allergies;
}

Now, if you want provide a way to add Allergies to the Allergies objects contained in the allergies field, you should provide a method addAllergies() :

public void addAllergies(List<Allergy> allergies) {
    this.allergies.addAll(allergies);
}

And you should also initialize the allergies field in its declaration (or in the constructor of Patient) :

private List<Allergy> allergies = new ArrayList<>();