显示从 Arraylist 中删除了哪些元素 [英] Show which elements are removed from Arraylist
本文介绍了显示从 Arraylist 中删除了哪些元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在编写一个非常简单的世界模拟器.每一步,人们都会变老,一旦达到最大年龄,他们就会死亡.我已经设法让人们死去并将他们从 ArrayList
中删除.但是,我想显示在每个时间步骤中有哪些人死亡(因此从 ArrayList
中删除了哪些元素),但我不知道该怎么做.这是我的代码:
I'm writing a very simple world simulator. Each time step, people get older, and once they reach a maximum age, they die. I already managed to let people die and to remove them from the ArrayList
. However, I would like to show which people died during each time step (so which elements are removed from the ArrayList
), but I don't know how to do it. This is my code:
for(Iterator<Person> personIterator = persons.iterator(); personIterator.hasNext();) {
Person person = personIterator.next();
if (person.getAge() >= Person.MAX_AGE){
personIterator.remove();
}
}
推荐答案
您可以将移除的元素累积到另一个集合中,然后返回/打印/不管它.例如:
You could accumulate the elements you remove to another collection, and then return/print/whatever it. E.g.:
List<Person> deaths = new LinkedList<>();
for(Iterator<Person> personIterator = persons.iterator(); personIterator.hasNext();) {
Person person = personIterator.next();
if (person.getAge() >= Person.MAX_AGE) {
deaths.add(person);
personIterator.remove();
}
}
这篇关于显示从 Arraylist 中删除了哪些元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文