public class Person {
private String name;
private boolean adopted;
private String parent;
private List<String> children;
public Person(String Aname) {
name = Aname;
children = new ArrayList<String>();
adopted = false;
}
public void adopt(Person person) {
if (!person.adopted && !person.name.equals(name)
&& children.size() <= 10) {
person.parent = name;
// System.out.println(parent);
// children=person.name;
for (int i = 0; i < children.size(); i++) {
children.add(i, person.name);
}
// System.out.println(children);
adopted = true;
}
}
public void setName(String name) {
this.name = name;
}
public void disown(Person person) {
}
public String toString() {
if (children.size() == 0 && parent == null) {
return name + " Parent: No parent. Children: No children ";
} else if (children.size() == 0) {
return name + " Parent: " + parent + " Children: No children";
} else if (parent == null) {
String list = null;
for (int i = 0; i < children.size(); i++) {
list = children.get(i);
}
return name + " Parent: No Parent " + "Children: " + list;
} else {
String list = null;
for (int i = 0; i < children.size(); i++) {
list = children.get(i);
}
return name + " Parent: " + parent + " Children: " + list;
}
}
}
在這我試圖將person.name添加到arraylist兒童,但我無法添加。我正在初始化列表,然後向列表中添加一個名稱。我正在使用採用方法將子項添加到列表中。請告訴我在這裏做錯了什麼。要添加一個元素到arraylist
你還沒有真正告訴我們什麼是錯的。你是否收到編譯器錯誤?沒有得到預期的輸出?什麼? –
我在輸出中沒有得到任何兒童的退化 – Hafiz