Hello, I had difficulties finishing this task because I could not wrap my head around on how to add object to various arraylists. But I checked other questions and answers to them and saw that I only need 1 array list, of children.
My questions are:
1. How does the following expression work: object.ArrayList.add(object) - father.children.add(child1) - I don't remember having encountered this expression before.
2. I tried to print the arraylist, to see if it contains all of the objects added, but it would not print. Why is that?
public class Solution {
public static void main(String[] args) {
//write your code here
Human grandfather1 = new Human("Grandpapi1", true, 87, new ArrayList<Human>());
Human grandfather2 = new Human("Grandpapi2", true, 84, new ArrayList<Human>());
Human grandmother1 = new Human("Granmami1", false, 82, new ArrayList<Human>());
Human grandmother2 = new Human("Grandmami2", false, 65,new ArrayList<Human>());
Human father = new Human("Papi", true, 56,new ArrayList<Human>() );
Human mother = new Human("Mami", false, 56,new ArrayList<Human>() );
Human child1 = new Human("Kiddo1", true, 28, new ArrayList<Human>() );
Human child2 = new Human("Kiddo2", false, 33, new ArrayList<Human>());
Human child3 = new Human("Kiddo3", true, 30, new ArrayList<Human>() );
ArrayList<Human> children = new ArrayList<>();
father.children.add(child1);
father.children.add(child2);
father.children.add(child3);
mother.children.add(child1);
mother.children.add(child2);
mother.children.add(child3);
grandfather1.children.add(father);
grandmother1.children.add(father);
grandfather2.children.add(mother);
grandmother2.children.add(mother);
System.out.println(father);
System.out.println(grandfather1);
System.out.println(grandfather2);
System.out.println(grandmother1);
System.out.println(grandmother2);
System.out.println(mother);
System.out.println(child1);
System.out.println(child2);
System.out.println(child3);
for (int i = 0; i < children.size(); i++) System.out.println(children.get(i));
}
public static class Human {
//write your code here
String name ;
boolean sex ;
int age;
ArrayList<Human> children;
Human (){}
Human (String name, boolean sex, int age){
this.name = name;
this.sex = sex;
this.age = age;
}
Human (String name, boolean sex, int age, ArrayList<Human> children){
this.name = name;
this.sex = sex;
this.age = age;
this.children = children;
}
public String toString() {
String text = "";
text += "Name: " + this.name;
text += ", sex: " + (this.sex ? "male" : "female");
text += ", age: " + this.age;
int childCount = this.children.size();
if (childCount > 0) {
text += ", children: " + this.children.get(0).name;
for (int i = 1; i < childCount; i++) {
Human child = this.children.get(i);
text += ", " + child.name;
}
}
return text;
}
}
}