如何遍历Hashtable,然后将对象添加到ArrayList?

时间:2014-09-07 04:06:21

标签: java

我正在制作家谱计划。我一直试图弄清楚如何将对象从Hashtable复制到ArrayList(只是对象Person,而不是String)。我有一个孩子的Hashtable,它们是Person对象。我想检查一下我在程序中工作的currentPerson是否有子节点,如果是,则将这些子节点添加到ArrayList子节点列表中。我已经在这方面工作了几个小时,似乎无法弄明白。

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;
    }

2 个答案:

答案 0 :(得分:0)

使用ArrayList addAll方法。

childList.addAll(children.get(currentPerson.getName())

答案 1 :(得分:0)

使用ArrayList addAll可以解决NG中提到的单行问题。

但是,如果您计划填写孙子列表,那么您需要更改存储数据的方式。由于您按名称存储内容,因此您无法确定答案是否正确。下面的代码将起作用,假设您的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] - &gt; [家长 - 鲍勃] - &gt; [孩子 - 山姆] - &gt; [GrandChild - 彼得]
[根] - &gt; [家长 - 山姆] - &gt; [孩子 - 鲍勃]

技术上只有一个grandChild,但根据您存储信息的方式,您的算法可能会返回两个。