3

I am having a few issues implementing this. I have an ArrayList. I have been looking for a few days now and I can't seem to find the answer anywhere:

private List<FamilyTree> Tree;

I can add new Trees to the array like this:

FamilyTree Generation = new FamilyTree();
Generation.add(new Tree());

I basically want to be able to move between the generations. So for example, I add a new Person to the tree

Generation.add(new Person(height, hair colour, eyes));

Then I decide, I want to add another person to the previous generation. That is to the Arraylist Containing the current ArrayList(not this one).

I am not sure if I am explaining my problem well so here is a diagram:

----John----Peter----Sandra----Rachel-----
   /   \       |       |
-Jon--Sunny---Cassie--Milo---
                     /  |  \
                   Ron-Kim-Guy

So Basically, there is an initial ArrayList of John, Peter, Sandra and Rachel. Each having their own Arraylist(s). Supposing I want to add to Rachel from Guy, how would I move back and forth between the separate arrays??

Thanks in advance

Nishant
  • 32,082
  • 5
  • 39
  • 53
Ester
  • 143
  • 1
  • 3
  • 12
  • Your question is not clear at all, and you show no meaningful code. But I have the feeling that you just need `rootPersons.remove(rachel); guy.addChild(rachel);`. Please stick to Java naming conventions: variables start with a lower-case letter. – JB Nizet Apr 16 '12 at 11:13

3 Answers3

4

If each person has two parents and any number of children, you can use a structure like

class Person {
   final Person mother, father;
   final List<Person> children = new ArrayList<>();

   public Person(Person mother, Person father) {
     this.mother = mother;
     this.father = father;
     mother.addChild(this);
     father.addChild(this);
   }

   public void addChild(Person p) {
     children.add(p);
   }
}

If you want to move up the materal line you can do something like

for(Person p = ...; p != null; p = p.mother) {

}

Instead of thinking about how you would display the tree, you should thiink about how its represented.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
1

You don't need a multidimensional list but a tree. See this question for an implementation of a tree.

Multi-dimensional list are for example tables, cuboids and so on. The dimension must be known at the beginning and defines the structure of the data.

Trees have root nodes and children, and those children can get more children at runtime, so there is no limit.

Community
  • 1
  • 1
Yogu
  • 9,165
  • 5
  • 37
  • 58
1

The easiest way is each of the list's to have a reference to it's parent. Maybe if you create an object Person similar to this:

public class Person{

ArrayList<Person> childs;//the child's nods
Person parent; //the parent, null if is the root

}
Vítor Marques
  • 349
  • 4
  • 11