![](/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.