Java:使用.add(new Methodname())将一组String值添加到ArrayList中的每个元素

时间:2015-11-28 12:34:48

标签: java arraylist

我不确定我是否正确发布了问题,但这是问题所在。我知道您可以将String或int值添加到ArrayList的元素中。但我希望每个元素都是一组字符串firstname,lastname和一个关系值(理想情况下)。我不知道这是否对ArrayList要求太多,但它是理想的。

这是ArrayList

ArrayList<Member> family = new ArrayList<Member>(); 
    family.add(new Member());
    family.add(new Member());
    family.add(new Member());
    family.add(new Member());

    for(Member dad : family){
        dad.setFirstName("Father");
        dad.setLastName("Last");
     }

    for(Member mom : family){
        mom.setFirstName("Mother");
        mom.setLastName("Last");
    }

    for(Member son : family){
        son.setFirstName("Son");
        son.setLastName("Last");
    }

    for(Member daughter : family){
        daughter.setFirstName("Daughter");
        daughter.setLastName("Last");
    }

Member是一个用于获取/设置这些值的类,以及用于在控制台上获取输出的覆盖。

然而,当我打印到控制台时,我得到一个完全错误的答案。我得到最后一个元素女儿的四倍,每次四次:

[Member (firstname=Daughter, lastname=Last), Member (firstname=Daughter, lastname=Last), Member (firstname=Daughter, lastname=Last), Member (firstname=Daughter, lastname=Last)]
[Member (firstname=Daughter, lastname=Last), Member (firstname=Daughter, lastname=Last), Member (firstname=Daughter, lastname=Last), Member (firstname=Daughter, lastname=Last)]
[Member (firstname=Daughter, lastname=Last), Member (firstname=Daughter, lastname=Last), Member (firstname=Daughter, lastname=Last), Member (firstname=Daughter, lastname=Last)]
[Member (firstname=Daughter, lastname=Last), Member (firstname=Daughter, lastname=Last), Member (firstname=Daughter, lastname=Last), Member (firstname=Daughter, lastname=Last)]

是什么给出了?

BTW,这就是我用来打印的内容:

    @Override
public String toString() {
    return "Member (firstname=" + firstname + ", lastname=" + lastname + ")";
}

1 个答案:

答案 0 :(得分:1)

代码中的每个下一个for循环都会重置前一个family列表中更新的值。这就是为什么你的列表只有最后一次迭代设置的值。