Всем добрый день!
Не могу понять механику добавления объекта в ArrayList в конструкторе. Не помню чтобы проходили этот момент в курсе и нагуглить что-то не получается. Может быть есть какая-то статья, или документация по этому поводу???
Заранее благодарю Вас!
Мой код на текущий момент.
public class Solution {
public static void main(String[] args) {
Human kid1 = new Human("Максим", true,33);
Human kid2 = new Human("Вася", true,33);
Human kid3 = new Human("Ира", false,30);
Human father = new Human("Евгений", true, 52, new ArrayList<Human>());
Human mother = new Human("Людмила", false, 50);
Human grandMa1 = new Human("Мария",false,70);
Human grandPa1 = new Human("Иван",true,68);
Human grandMa2 = new Human("Нина",false,78);
Human grandPa2 = new Human("Евгений",true,65);
System.out.println(father);
}
public static class Human {
String name;
boolean sex;
int age;
ArrayList<Human> children;
public Human(String name, boolean sex, int age) {
this.name = name;
this.sex = sex;
this.age = age;
}
public Human(String name, boolean sex, int age, ArrayList<Human> children){
this.name = name;
this.sex = sex;
this.age = age;
children.add(this);
}
public String toString() {
String text = "";
text += "Имя: " + this.name;
text += ", пол: " + (this.sex ? "мужской" : "женский");
text += ", возраст: " + this.age;
int childCount = this.children.size();
if (childCount > 0) {
text += ", дети: " + this.children.get(0).name;
for (int i = 1; i < childCount; i++) {
Human child = this.children.get(i);
text += ", " + child.name;
}
}
return text;
}
}
}