StievieG
StievieG

Reputation: 95

Show which elements are removed from 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();
    }
}

Upvotes: 2

Views: 72

Answers (4)

njasi
njasi

Reputation: 126

When you use the remove method in the ArrayList class, it will return what you removed. So I think you could have something store the people that die, namely another ArrayList. So something like this should work:

ArrayList<person> dead = new ArrayList<person>();
if (person.getAge() >= Person.MAX_AGE){
             dead.add(personIterator.remove());
            }

P.S. I'm extremely new to coding so this may not work... I learned how to use arrays and ArrayLists yesterday. (This code assumes that there is a person class that the stuff is in)

Upvotes: 0

Mureinik
Mureinik

Reputation: 311938

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();
    }
}

Upvotes: 1

myselfmiqdad
myselfmiqdad

Reputation: 2606

Create a new list and add to that

for (Iterator < Person > personIterator = persons.iterator(); personIterator.hasNext();) {
 Person person = personIterator.next();
 if (person.getAge() >= Person.MAX_AGE) {
  personIterator.remove();
  personDead.add(person); // ADDED THIS LINE OF CODE
 }
}

Upvotes: 0

Rogue
Rogue

Reputation: 11483

You have a variety of options, one could be simply having a #die method on the Person class which reports however you like:

public class Person {

    public void die() {
        System.out.println("Old man Jenkins kicked the bucket");
    }

}

//Elsewheres
if (person.getAge() >= Person.MAX_AGE) {
    person.die();
    //remove
}

If you need to reference them at a later point, then you can add them to another collection.

Upvotes: 0

Related Questions