私はジェネリックとツリー構造を理解しようとしており、次の問題に固執しています...
私は3つのクラスを作成しました1)Node 2)Person 3)NodeTest
import java.util.*;
public class Node<T>
{
private Node<T> root; // a T type variable to store the root of the list
private Node<T> parent; // a T type variable to store the parent of the list
private List<Node<T>> children = new ArrayList<Node<T>>(); // a T type list to store the children of the list
// default constructor
public Node(){ }
// constructor overloading to set the parent
public Node(Node<T> parent)
{
this.setParent(parent);
//this.addChild(parent);
}
// constructor overloading to set the parent of the list
public Node(Node<T> parent, Node<T> child)
{
this(parent);
this.children.add(child);
}
public void addChild(Node<T> child)
{
this.children.add(child); // add this child to the list
}
public void removeChild(Node<T> child)
{
this.children.remove(child); // remove this child from the list
}
public Node<T> getRoot() {
return root;
}
public boolean isRoot()
{
return this.root != null; // check to see if the root is null if yes then return true else return false
}
public void setRoot(Node<T> root) {
this.root = root;
}
public Node<T> getParent() {
return parent;
}
public void setParent(Node<T> parent) {
this.parent = parent;
}
public boolean hasChildren()
{
return this.children.size()>0;
}
public Node<T>[] children()
{
return (Node<T>[]) children.toArray(new Node[children.size()]);
}
public Node<T>[] getSiblings()
{
if(this.isRoot()==false)
{
System.out.println("this is not root");
}
List<Node<T>> tempSiblingList = new ArrayList<Node<T>>();
//this.parent.children() isn't working for me
//hence i tried to get around it next two lines
Node<T> parent = this.parent;
Node<T>[] children = parent.children();
for(int i=0; i<children.length; i++)
{
if(this!=children[i])
{
tempSiblingList.add(children[i]);
}
}
return (Node<T>[]) tempSiblingList.toArray(new Node[children.length]);
}
}
public class Person {
private String name;
private int age;
private String status;
public Person(String name, int age, String status)
{
this.setName(name);
this.setAge(age);
this.setStatus(status);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
私の質問は、Node クラスの Person クラスを初期化する方法です...
私が試してみました
Person rootPerson = new Person("root", 80, "Alive");
Node<Person> root = new Node<Person>(rootPerson);
しかし、それは私にはうまくいきません...
getSibilings() のヘルプも必要です