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
3 Answers 3
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.
Comments
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.
Comments
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
}
Comments
Explore related questions
See similar questions with these tags.
rootPersons.remove(rachel); guy.addChild(rachel);. Please stick to Java naming conventions: variables start with a lower-case letter.