![](/img/trans.png)
[英]How to add to an ArrayList that is a HashMap value while iterating?
[英]How to add items found while iterating to an ArrayList?
ArrayList<Persons> persList = new ArrayList<Persons>();
for(Persons p : persList){
Persons pers = new Persons();
pers = service.getPersons(id);
p.setAddress(pers.getAddress());
persList.add(pers);
}
这是将所有找到的人员添加到persList的正确方法吗? 先感谢您。
不可以,除了通过Iterator.remove
方法外,在遍历列表时不应修改列表。 除此以外,即使这段代码没有引发异常,它也将永远persList
下去,除非persList
为空...总是有新的人来迭代!
您基本上应该创建一个新列表来收集要添加的项目,然后在末尾使用addAll
:
ArrayList<Persons> persList = new ArrayList<Persons>();
// Populate the list, presumably
List<Persons> extraPeople = new ArrayList<Persons>();
for(Persons p : persList){
// Note: there's no point in creating a new object only to ignore it...
Persons pers = service.getPersons(id);
p.setAddress(pers.getAddress());
extraPeople.add(pers);
}
persList.addAll(extraPeople);
在我看来,这段代码仍然没有多大意义,因为您每次迭代都通过相同的id
值来获取...我只能希望这是一个示例,而不是真实的代码。
还要注意,如果您的Persons
类的每个实例都打算是一个单独的人,则最好将其称为Person
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.