Нашел в комментариях идею решения через VarArgs от пользователя vk
Заинтересовало и хочу её реализовать.
Здесь в вопросе по задаче: Как упростить? есть объяснения, но мне кое-что непонятно.
1. Почему в поле класса Human (42-я строка) мы добавляем переменной класса модификатор final? Для чего он? Что делает? Ведь динамический массив по умолчанию длиной 10 элементов и заполнен в данном случае объектами, которые содержат ссылки null. Что я не понимаю?
2. 56 строка подчеркивается красной волнистой линией. Почему? Пытался после package импортировать List - не помогло.
3. 55-56 строкию Цитата из ссылки: то есть с 4 и далее аргумента можно использовать аргументы класса Human, и они будут собраны в единый массив Human[] children. Методом Arrays.asList мы преобразуем этот массив в список и вызовем второй конструктор с полученным набором аргументов. Подчеркнутое не понял. Если есть возможность - разъясните, пожалуйста.
package com.javarush.task.task08.task0824;
/*
Собираем семейство
*/
import java.util.ArrayList;
import java.util.Arrays;
public class Solution {
public static void main(String[] args) {
//напишите тут ваш код
//Создай объекты и заполни их так, чтобы получилось: два дедушки, две бабушки, отец, мать, трое детей
Human child1 = new Human("Петя", true, 6);
Human child2 = new Human("Витя", true, 3);
Human child3 = new Human("Саша", true, 4);
Human father = new Human("Сергей", true, 32, child1, child2, child3);
Human mother = new Human("Тамара", false, 30, child1, child2, child3);
Human grandFather1 = new Human("Геннадий", true, 65, father);
Human grandFather2 = new Human("Василий", true, 67, mother);
Human grandMother1 = new Human("Светлана", false, 58, father);
Human grandMother2 = new Human("Галина", false, 54, mother);
System.out.println(child1);
System.out.println(child2);
System.out.println(child3);
System.out.println(father);
System.out.println(mother);
System.out.println(grandFather1);
System.out.println(grandFather2);
System.out.println(grandMother1);
System.out.println(grandMother2);
}
public static class Human {
//напишите тут ваш код
private String name;
private boolean sex;
private int age;
final private ArrayList<Human> children = new ArrayList<>();
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, sex, age);
this.children.addAll(children);
}
public Human(String name, boolean sex, int age, Human ... children) {
this(name, sex, age, Arrays.asList(children));
}
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;
}
}
}