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
2nd-name-> 仅打印最后一行 50 次,而 1st-name-> 则打印全部 50 行。为什么会发生这种情况?
最佳答案
这是因为第一个循环不断覆盖相同的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
实例。
关于java - 列表迭代器仅返回最后一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25561948/