java - 列表迭代器仅返回最后一行

标签 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

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/

相关文章:

java - Firebase 填充 recyclerview 错误 : com. firebase.client.FirebaseException: Failed to bounce to type

java - 如何让重载方法识别泛型类型的特定子类?

python 根据两个列表创建嵌套目录

java - 对来自 GAE 数据存储的查询响应进行排序

multithreading - 使用Groovy的GPar,何时需要使用collectParallel()进行显式同步?

java - 如何从反馈列表中以最小顺序查找每个用户给出的最新反馈?

java.sql.SQLSyntaxErrorException : Columns of type 'INTEGER' cannot hold values of type 'CHAR'

java 并发 - 中断 DeadLook 线程

c# - 检查两个列表是否有相同的项目

Java 继承 : Restrict List to Subclass Objects