Array within an array

Ok so im writting this game and I so far the world is randomly generated, this means that vegetation(trees, plants etc.)spawn all over the place. To prevent overlapping I created a method that would delete one “vegetation” if its touching another as seen in the source code below:

for (Vegetation c: Object_Control.Vegetationarray) {
			for (Vegetation i: Object_Control.Vegetationarray) {
				if (c.getImageBounds().intersects(i.getImageBounds())) {
					Object_Control.removeVegetation(c);
				}
			}
		}

The “getImageBounds()” method returns a rectangle that is the same size as the image.

The error I seem to be getting is:

Exception in thread "AWT-EventQueue-0" java.util.ConcurrentModificationException

I am happy to supply any more source code related to the issue if needed

I assume Object_Control.Vegetationarray is a collection such as an ArrayList?

Essentially what the for loop is attempting to do is modify the collection at the same time you are iterating over it, hence the exception.

Two ways round this:

  1. Get an iterator from the collection and use Iterator.remove() (not supported by all collections mind and probably not the best approach for this case anyway).

  2. Create a new list of objects to be removed and then remove them in a second step.

i.e.


List<Vegetation> removed = new ArrayList<>();
for(...) {
    for(...) {
        if( ... ) removed.add( c );
    }
}
Object_Control.Vegetationarray.removeAll( removed );

  • stride

In addition to what stride said, with the double enhanced for loop, if i’m not mistaken. You are comparing every vegetation with itself + all others? Wont that mean every vegatation intersects with itself, meaning your deleting all vegetation in the game :o. Try doing a normal double for loops up to arrays size, but in the inner for loop have an if statement to ensure your not comparing the same vegation.
eg if(!c.equals(i) && c.getImageBounds.inter etc… Then need to remove it.

You were right, it does delete all vegetation. So what were you explaining im having trouble understanding your method

Well you would do it like stride said, but just change the inner loop
eg


for(int c = 0; Object_Control.Vegetationarray.size(); c++)
  for( i = 0; Object_Control.Vegetationarray.size(); i++)

    //get the two vegations you want to compare.
    Vegation vegation = Object_Control.Vegetationarray.get(i);
    Vegation vegationToCompare = Object_Control.Vegetationarray.get(c);
    
    //compare them, removing if they interect put ensuring they not the same vegation also.
    if(!vegation .equals(vegationToCompare) && vegationToCompare .getImageBounds().intersects(vegationToCompare.getImageBounds()))
    remove.add(i)

This !c.equals(i) ensures that you are not going to remove any vegetation if they are the same.

Thanks this worked a treat. :slight_smile: