List iterator仅返回最后一行

时间:2014-08-29 04:59:53

标签: java list collections iterator

Iterator<Account> entitiesItr = entities.iterator();
List<AccountSync> accountsList = new ArrayList<AccountSync>();
AccountSync accountsync = new AccountSync();
while (entitiesItr.hasNext()) {
    Account account = (Account) entitiesItr.next();
    accountsync.setAccountName(account.getName());
    accountsList.add(accountsync);
    System.out.println("1st-name->"+account.getName());
}

Iterator<AccountSync> it = accountsList.iterator();
while (it.hasNext()) {
    AccountSync accountSync2 = (AccountSync) it.next();
    System.out.println("2nd-name->"+accountSync2.getAccountName());
        }

输出:

1st-name->Sun
1st-name->Oracle
1st-name->google
...
1st-name->Yahoo



2nd-name->Yahoo
2nd-name->Yahoo
2nd-name->Yahoo
2nd-name->Yahoo
....50 times

第二-名称 - &GT;仅打印最后一行50次,而1st-name-&gt;它打印所有50行。为什么会这样?

2 个答案:

答案 0 :(得分:3)

这是因为第一个循环会覆盖相同的AccountSync。 试试这种方式:

AccountSync accountsync;
while (entitiesItr.hasNext()) {
    accountsync = new AccountSync();
    Account account = (Account) entitiesItr.next();
    accountsync.setAccountName(account.getName());
    accountsList.add(accountsync);
    System.out.println("1st-name->"+account.getName());
}

在这种情况下,每个实体都将拥有自己的AccountSync实例。

答案 1 :(得分:0)

你需要搬家

AccountSync accountsync = new AccountSync();

到你的while循环内部,否则你使用相同的一个并只是更新它。