![](/img/trans.png)
[英]How do I iterate through an ArrayList of custom objects from Intent and add them into LinearLayout?
[英]How do I iterate through a Hashtable, then add the objects to an ArrayList?
我正在制作家譜程序。 我一直試圖找出如何將對象從哈希表復制到ArrayList(只是對象Person,而不是String)。 我有一個孩子的哈希表,它們是Person對象。 我想檢查我在程序中正在使用的currentPerson是否有子項,如果有,將這些子項添加到ArrayList childList中。 我已經為此工作了幾個小時,似乎無法弄清楚。
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Hashtable;
public class FamilyInfo {
//////////// instance variables
// hash table that tells the father of a named person, if known
private Hashtable<String, Person> fathers;
// hash table that tells the mother of a named person, if known
private Hashtable<String, Person> mothers;
// hash table that tells the children of a named person, if any are known.
// In theory the father, mother and children tables should be kept consistent
private Hashtable<String, HashSet<Person>> children;
/**
* constructor -- initializes instance variables
*/
public FamilyInfo() {
// initialize everything to be empty collections of the appropriate type
fathers = new Hashtable<String, Person>();
mothers = new Hashtable<String, Person>();
children = new Hashtable<String, HashSet<Person>>();
}
public ArrayList<String> grandchildNames(Person currentPerson) {
// return a dummied up name telling that the method is not implemented
ArrayList<String> rtnVal = new ArrayList<String>();
//Create an ArrayList that will hold the child
ArrayList<Person> childList = new ArrayList<Person>();
//Create an ArrayList that will hold the granchildren
ArrayList<Person> grandchildList = new ArrayList<Person>();
//Add children to the child list
if(children.get(currentPerson.getName()) != null)
{
//add the children to childList from the children hashtable
}
return rtnVal;
}
使用ArrayList addAll方法。
childList.addAll(children.get(currentPerson.getName())
使用ArrayList addAll可以解決NG中提到的問題。
但是,如果您還計划填充grandchildList,則需要更改存儲數據的方式。 由於您是按名稱存儲東西,因此您永遠無法真正弄清楚答案是否正確。 假設您的Person類具有按名稱列出的子級列表,則以下代碼將起作用。
if (children.containsKey(currentPerson.getName()) {
for (Person c : children.get(currentPerson.getName())) {
childList.add(c);
//Now assuming Person class keeps a list of children names
if (c.getChildren() != null) {
grandchildList.addAll(c.getChildren());
}
}
}
考慮這種情況:
[Root]-> [Parent-Bob]-> [Child-Sam]-> [GrandChild-Peter]
[Root]-> [Parent-Sam]-> [Child-Bob]
從技術上講,只有一個grandChild,但是您的算法可能會返回兩個,這取決於您存儲信息的方式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.