0

I have written 3 class: Animal,Location,MainClass

Animal class stores the age and health of animal. health = 1 is healthy, health = 0 is injured.

Location class creates a array list of Animal class. Using the MainClass I am adding values to arraylist in location class.

I'm trying to remove all the all the animals that are injured from the arraylist. I see that only some of the elements are removed.

Animal Class

class Animal
{
    private int age;
    private int health;

    public Animal(int newAgeValue,int newHealthValue)
    {
        age = newAgeValue;
        health = newHealthValue;
    }

    public int getAge()
    {
        return age;
    }
    
    public void setAge(int newAgeValue)
    {
        age = newAgeValue;
    }
    
    public int getHealth()
    {
        return health;
    }
    
    public void setHealth(int newHealthValue)
    {
        health = newHealthValue;
    }
    
    public boolean contains(int newAgeValue,int newHealthValue)
    {
        if (newAgeValue == age && newHealthValue == health)
            return true;
        return false;
    }
    public String toString()
    {
        return "Age of Animal: " + Integer.toString(getAge()) + " Health: " + Integer.toString(getHealth());
    }
}

Location Class

import java.util.ArrayList;
class Location
{
    private ArrayList<Animal> animals = new ArrayList<>();

    public void addAnimal(int newAgeValue,int newHealthValue)
    {
        animals.add(new Animal(newAgeValue,newHealthValue));
    }

    public ArrayList<Animal> getAnimal()
    {
        return animals;
    }
    public boolean removeAnimal(int newAgeValue,int newHealthValue)
    {
        for (int i =0;i<animals.size();i++)
        {
            Animal newAnimal = animals.get(i);
            if (newAnimal.contains(newAgeValue,newHealthValue))
            {
                animals.remove(i);
                return true;
            }
        }
        return false;
    }

    public int InjuredAnimal()
    {
        int numberOfDeath = 0;
        System.out.println("Size of animals: "+ animals.size());
        for (int i = 0; i < animals.size() ; i++)
        {
            System.out.println("Inside InjuredAnimal(): "+ animals.get(i));
            if ( animals.get(i).getHealth() == 0)
            {
                numberOfDeath++;
                removeAnimal(animals.get(i).getAge(), 0);
            }   
        }
        return numberOfDeath;
    }
}

Main Class

public class MainClass 
{
    public static void main(String[] args) 
    {
        Location loc = new Location();
        loc.addAnimal(15, 1);
        loc.addAnimal(10, 0);
        loc.addAnimal(1, 0);
        loc.addAnimal(11, 1);
        loc.addAnimal(18, 0);
        loc.addAnimal(10, 0);
        loc.addAnimal(1, 0);
        loc.addAnimal(15, 1);
        loc.addAnimal(18, 0);
        loc.addAnimal(18, 0);
        loc.addAnimal(10, 0);
        
        System.out.println("Animals added.");
        ArrayList<Animal> animals = loc.getAnimal();
        for(int i = 0;i<animals.size();i++)
        {
            System.out.println(animals.get(i));
        }
        int deathValue = loc.InjuredAnimal();
        System.out.println("Killed Value: " + deathValue);
        for(int i = 0;i<animals.size();i++)
        {
            System.out.println(animals.get(i));
        }

    }    
}

Output

Animals added.
Age of Animal: 15 Health: 1
Age of Animal: 10 Health: 0
Age of Animal: 1 Health: 0
Age of Animal: 11 Health: 1
Age of Animal: 18 Health: 0
Age of Animal: 10 Health: 0
Age of Animal: 1 Health: 0
Age of Animal: 15 Health: 1
Age of Animal: 18 Health: 0
Age of Animal: 18 Health: 0
Age of Animal: 10 Health: 0
Size of animals: 11
Inside InjuredAnimal(): Age of Animal: 15 Health: 1
Inside InjuredAnimal(): Age of Animal: 10 Health: 0
Inside InjuredAnimal(): Age of Animal: 11 Health: 1
Inside InjuredAnimal(): Age of Animal: 18 Health: 0
Inside InjuredAnimal(): Age of Animal: 1 Health: 0
Inside InjuredAnimal(): Age of Animal: 18 Health: 0
Inside InjuredAnimal(): Age of Animal: 10 Health: 0
Killed Value: 5
Age of Animal: 15 Health: 1
Age of Animal: 11 Health: 1
Age of Animal: 1 Health: 0
Age of Animal: 15 Health: 1
Age of Animal: 18 Health: 0
Age of Animal: 10 Health: 0

ArrayList has removed only some of injured animals. I'm looking to remove all of it. What could be the reason for this? help would be appreciated.

Community
  • 1
  • 1
  • Does this answer your question? [Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop](https://stackoverflow.com/questions/223918/iterating-through-a-collection-avoiding-concurrentmodificationexception-when-re) – PatrickChen Jun 04 '20 at 02:42
  • 1
    You should use `iterating` to remove elements inside the collection not delete in for loop – PatrickChen Jun 04 '20 at 02:43
  • @patrick This helped. Thanks :) – Sampreeth Amith Kumar Jun 04 '20 at 02:56
  • 1
    When you say you want to “remove all the all the animals that are injured”, why don’t you do that but call another method to remove all animals passing a “`contains(newAgeValue,newHealthValue)`” test? A straight-forward removal of all animals with zero health would be `animals.removeIf(a -> a.getHealth() == 0)`. Adapting the `numberOfDeath` could be done by using the size difference. – Holger Jun 04 '20 at 13:43

1 Answers1

2

Your list is [1,2,3,4,5,6].

Iteration starts as i = 0. First element of the list ('1') is checked, and let's say, removed. Your list is now [2,3,4,5,6]. i is now equal to 1.

Now you check whatever list.get(1) returns which is... 3.

The 2 was skipped.

You can't remove elements like this. Either index 'from the end' (loop from the end to the start, instead of from the start to the end), or better yet, make an iterator, iterate, and use iterator's remove method instead.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72