1
  public void removeVehicle(String licenseNum){      

      for (Vehicle vehicle : vehicleLot){

    String flag = vehicle.getLicenseNumber().toString();
        if(flag.compareTo(licenseNum) == 0){
            int num = vehicleLot.indexOf(vehicle);

        vehicleLot.remove(num);
    }

I am getting this exception, I am trying to remove a vehicle from a array list where it matched the license number like above.

my array list is like this private

 List<Vehicle> vehicleLot = new ArrayList<Vehicle>();
1
  • It's "CONcurrent modification exception" -- you're modifying something concurrent with it being iterated. Don't do that. (At least not that way.) Commented Aug 15, 2014 at 1:11

3 Answers 3

2

You cannot remove an element from an ArrayList that you are iterating through using an Iterator (which is what for(element : list) uses under the covers) unless you use the iterator itself to remove the item.

What you can do is to iterate through the list using a declared iterator, or via numeric index to avoid the issue.

E.g.

Iterator<Vehicle> iterator = vehicleLot.iterator();
while(iterator.hasNext())
{
  Vehicle vehicle = iterator.next();
  String flag = vehicle.getLicenseNumber().toString();
  if(flag.compareTo(licenseNum) == 0)
  {
    iterator.remove();
  }

}
Sign up to request clarification or add additional context in comments.

2 Comments

could you please exapand on this? I am not sure what you mean how would i combine delcared iterator and the above for each
@purplehaze Replace your foreach with the while loop I have provided.
1

The foreach loop in java is not a true runtime feature. It's just syntax to replace one of two loops.

On those that implement Iterable< T > the loop is effectively

Iterator< T > itr = list.iterator();
while( itr.hasNext() ) {
    T t = itr.next();
    // Loop stuff
}

This means you can not edit the List in a foreach loop without causing an exception and you must abide by all the restrictions set in place when using Iterators without the benefit of having access to the iterator.

On array's it is effectively

T[] arr = ...;
for( int i = 0; i < arr.length; i++ ) {
    T elm = arr[ i ];
    // Loop stuff
}

1 Comment

could you possible expand on the solution? how would i use this Itertor on my above loop?
0

The old way to handle this (before fancy iterators) was:

public void removeVehicle(String licenseNum){      
    for (int i = vehicleLot.size() - 1; i >= 0; i--) {
        Vehicle vehicle = vehicleLot.get(i);
        String flag = vehicle.getLicenseNumber().toString();
        if (flag.equals(licenseNum)) {
           vehicleLot.remove(i);
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.