java update all children in list

73 views Asked by At

So Let's say I have a List of Persons that are related to each other and each contains their own family tree.

public class Person {
  private int id;
  private String name;
  private List<Integer> ancestorIds;
  private int parentId;
  //getters and setters
}

so let's say I have the list as following:

List<Person> persons = new ArrayList<Person>();
persons.add(new Person(3,"grandpa", {}, null));
persons.add(new Person(4,"pa", {3,4},3));
persons.add(new Person(5,"uncle", {3,5},3));
persons.add(new Person(7,"me", {3,4,7},4));

But now we know that my grandpa his father was actually the one with id 1.. And i need to update the list.. How can I do this keeping in mind that I need to update it by line.. So first my grandpa.. Then taking the ancestorids list of him and give it to my pa and uncle (adding their ids as well). and then me taking the list of my pa and adding me. I think I need some recursive method for this.

Thanks in advance

2

There are 2 answers

0
Kai On

If you make changes on this data structure it would be more flexible if you let each person point to it's direct ancestor only. And then build the tree on demand. The way you mentioned in your question I would use if the tree don't gets changed.

1
Elias On

Are you forced to use this representation? It would make more sense for the family tree to reference Persons, in particular, for the Person class to be defined as:

public class Person {
      private int id;
      private String name;
      private List<Person> ancestors;
      private int parentId;
      //getters and setters
    }

If done in this way, you don't need to update anything, except for your great grandfather. In fact, doing it line-by-line isn't a robust solution, since there's room for error (if you miss a single ID), and you should avoid this, to have good design. Even worse, unless you keep backpointers (i.e. have descendants as well as ancestors), there is no efficient way to update ancestors down the tree.