• Najnowsze pytania
  • Bez odpowiedzi
  • Zadaj pytanie
  • Kategorie
  • Tagi
  • Zdobyte punkty
  • Ekipa ninja
  • IRC
  • FAQ
  • Regulamin
  • Książki warte uwagi

Budowa hierarchii z kolekcji elementów

Cloud VPS
0 głosów
368 wizyt
pytanie zadane 15 października 2022 w Java przez MKolaj15 Bywalec (2,270 p.)

Cześć, mam klasę o nazwie HierarchyBuilder<TItem>,  której parametr typu będzie ograniczał się tylko do klas  implementujących interfejs  IHaveHierarchicalStructure<TItem> posiadający następujące metody:

public interface IHaveHierarchicalStructure<TItem> {

    void setParent(TItem geography);

    List<TItem> getChildren();

    TItem getParent();

    int getId();

    Integer getParentId();
}

Jedną z takich klas jest Geography przedstawiona poniżej:

public class Geography implements IHaveHierarchicalStructure<Geography> {
    private int id;
    private String name;
    private String type;
    private String code;
    private Integer parentId;
    private Geography parent;
    private List<Geography> children = new ArrayList<>();

    @Override
    public void setParent(Geography parent) {
        this.parent = parent;
    }

    @Override
    public List<Geography> getChildren() {
        return children;
    }

    @Override
    public Geography getParent() {
        return parent;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public Integer getParentId() {
        return parentId;
    }

    public void setParentId(Integer parentId) {
        this.parentId = parentId;
    }
}

Klasa HierarchyBuilder ma posiadać następujące metody: 

HierarchyBuilder<Geography> geographyHierarchyBuilder = new HierarchyBuilder<>();
geographyHierarchyBuilder.setElements(geographies); //Niech builder przyjmie kolekcje geografii wygenerowany wcześniej

geographyHierarchyBuilder.buildHierarchy(); // niech zbuduje hierarchie

Geography rootGeography = geographyHierarchyBuilder.getRootElement();// niech zwróci rodzica wszystkichj geografii, czyli 'world'

Oto moja próba implementacji tych metod, niestety, nie jest ona poprawna:

public class HierarchyBuilder<TItem extends IHaveHierarchicalStructure<TItem>> {


    private List<TItem> items;

    public void setElements(List<TItem> items) {
        this.items = items;
    }

    public void buildHierarchy() {
        for (TItem item : items) {
            for (TItem children : item.getChildren())
                if(children.getParentId() == null) {
                    children.setParent(null);
                } else {
                    if(children.getParentId() == item.getId())
                    children.setParent(item);
                }
        }
    }

    public TItem getRootElement() {
        TItem world = null;
        for (TItem item : items) {
            if(world == null || item.getChildren().size() > world.getChildren().size()) {
                world = item;
            }
        }
        return world;
    }
}

 

Domyślam się, że błąd w metodzie buildHierarchy() polega na tym, że tą drugą pętlą foreach przeszukujemy pustą listę, ponieważ na początku nigdzie nie dodajemy elementów do listy children. Problem polega na tym, że nie wiem w jaki sposób to zrobić. Czy ktoś byłby w stanie pomóc mi w tym zadaniu? Z góry dziękuję.

komentarz 15 października 2022 przez Wiciorny Ekspert (281,530 p.)
Niech builder przyjmie kolekcje geografii wygenerowany wcześniej

A jak wygląda ta zbudowana kolekcja? 

komentarz 15 października 2022 przez MKolaj15 Bywalec (2,270 p.)

Jest jedna klasa z listą Stringów:

public class SampleGeographiesData {

    public static List<String> data = List.of(
            /*  id; typ regionu; nazwa regionu; kod regionu; id rodzica  */
            "1;World;World;;NULL                                                                                                    ",
            "2;County;Iraq-Kurdistan;;115                                                                                           ",
            "10;Country;Afghanistan;AF;4552                                                                                         ",
            "11;Country;Åland Islands;AX;4564                                                                                       ",
            "12;Country;Albania;AL;4554                                                                                             ",
            "13;Country;Algeria;DZ;4545                                                                                             ",
            "14;Country;American Samoa;AS;4558                                                                                      ",
            "15;Country;Andorra;AD;4554                                                                                             ",
            "16;Country;Angola;AO;4546...

Druga klasa z funkcją zamieniającą Stringa na obiekt klasy Geography:

public class GeographyParser implements IParse<Geography> {

    @Override
    public Geography parse(String line) {
        Geography geography = new Geography();
        String[] data = line.trim().split(";");
        geography.setId(Integer.parseInt(data[0]));
        geography.setName(data[1]);
        geography.setType(data[2]);
        geography.setCode(data[3]);
        if (data[4].equals("NULL")){
            geography.setParentId(null);
        } else {
            geography.setParentId(Integer.valueOf(data[4]));
        }
        return geography;
    }
}

I w klasie main mamy pętlę, która po kolei zamienia każdą linię na taki obiekt i dodaje go do listy geographies: 

List<Geography> geographies = new ArrayList<>();
        for (String line :
                SampleGeographiesData.data) {
            geographies.add(geographyParser.parse(line));
        }

 

Zaloguj lub zarejestruj się, aby odpowiedzieć na to pytanie.

Podobne pytania

0 głosów
0 odpowiedzi 400 wizyt
pytanie zadane 20 września 2019 w PHP przez michal_php Stary wyjadacz (13,700 p.)
0 głosów
2 odpowiedzi 615 wizyt
pytanie zadane 10 grudnia 2019 w JavaScript przez matedoo Nowicjusz (210 p.)
0 głosów
1 odpowiedź 157 wizyt
pytanie zadane 26 lipca 2023 w Java przez randomName Nowicjusz (220 p.)

93,466 zapytań

142,460 odpowiedzi

322,733 komentarzy

62,846 pasjonatów

Motyw:

Akcja Pajacyk

Pajacyk od wielu lat dożywia dzieci. Pomóż klikając w zielony brzuszek na stronie. Dziękujemy! ♡

Oto polecana książka warta uwagi.
Pełną listę książek znajdziesz tutaj

Kursy INF.02 i INF.03
...