1

Решение получилось слишком большое. Только учусь решать подобные задачи, не знаю как оптимизировать код, подскажите пожалуйста.

Задача:

  1. Создай класс Human с полями имя (String), пол (boolean), возраст (int), дети (ArrayList).
  2. Создай объекты и заполни их так, чтобы получилось: два дедушки, две бабушки, отец, мать, трое детей.
  3. Вывести все объекты Human на экран.

Решение:

import java.util.ArrayList;

public class Solution {
    public static void main(String[] args) {

        ArrayList <Human> children = new ArrayList  <> ();


        Human child1 = new Human("Петя", true, 15);
        Human child2 = new Human("Петя", true, 15);
        Human child3 = new Human("Надя", false, 15);
        children.add(child1);
        children.add(child2);
        children.add(child3);

        System.out.println(child1);
        System.out.println(child2);
        System.out.println(child3);

        Human father1 = new Human("Василий", true, 55, children);
        Human mother1 = new Human("Петр", true, 64, children);

        System.out.println(father1);
        System.out.println(mother1);

        children.clear();

        children.add(father1);
        children.add(mother1);

        Human grandPa1 = new Human("Василий", true, 55, children);
        Human grandPa2 = new Human("Петр", true, 64, children);
        Human grandMa1 = new Human("Василий", true, 55, children);
        Human grandMa2 = new Human("Петр", true, 64, children);

        System.out.println(grandMa1);
        System.out.println(grandMa2);
        System.out.println(grandPa1);
        System.out.println(grandPa2);


    }

    public static class Human {
        private String name;
        private boolean sex;
        private int age;
        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 = name;
            this.sex = sex;
            this.age = age;
            this.children = 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;
        }
    }

}
3
  • а что именно вы хотите оптимизировать? и еще ` children.clear();` разве вы не очищаете детей родителей? может проше сделат children = new ArrayList<>();
    – Saidolim
    26 дек 2015 в 11:33
  • 1
    @Saidolim, вообще лучше в конструкторе копию снимать с переданного списка. 26 дек 2015 в 11:36
  • 1
    @TagirValeev согласень так тоже можно. Постепенно автор пришел бы и на это тоже.
    – Saidolim
    26 дек 2015 в 11:44

1 ответ 1

6

В целом более-менее. Привыкайте, что Java вообще многословна. Я бы в одном конструкторе вызывал другой, не завязывался на конкретную реализацию List (писал просто List вместо ArrayList) и воспользовался бы Stream API в toString() (если можно использовать Java-8):

public static class Human {
    private String name;
    private boolean sex;
    private int age;
    private List < Human > children;

    public Human(String name, boolean sex, int age) {
        this(name, sex, age, Collections.emptyList());
    }

    public Human(String name, boolean sex, int age, List < Human > children) {
        this.name = name;
        this.sex = sex;
        this.age = age;
        this.children = children;
    }

    public String toString() {
        String text = "";
        text += "Имя: " + this.name;
        text += ", пол: " + (this.sex ? "мужской" : "женский");
        text += ", возраст: " + this.age;

        if (!this.children.isEmpty()) {
            text += ", дети: " + this.children.stream().map(child -> child.name)
                    .collect(Collectors.joining(", "));
        }

        return text;
    }
}

Ну и создать список объектов проще используя Arrays.asList (опять же не забывайте, что не на одном ArrayList свет клином сошёлся):

public static void main(String[] args) {
    List < Human > children = Arrays.asList(
            new Human("Петя", true, 15),
            new Human("Петя", true, 15),
            new Human("Надя", false, 15));

    children.forEach(System.out::println);

    Human father1 = new Human("Василий", true, 55, children);
    Human mother1 = new Human("Петр", true, 64, children);

    children = Arrays.asList(father1, mother1);
    children.forEach(System.out::println);

    Human grandPa1 = new Human("Василий", true, 55, children);
    Human grandPa2 = new Human("Петр", true, 64, children);
    Human grandMa1 = new Human("Василий", true, 55, children);
    Human grandMa2 = new Human("Петр", true, 64, children);

    Arrays.asList(grandMa1, grandMa2, grandPa1, grandPa2).forEach(System.out::println);
}

Вот импорты, если что:

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
1
  • 1
    Спасибо большое за ответ. 26 дек 2015 в 11:44

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.