-1
/**
 * Write a mehod that removes the movie with a given title
 */
public void removeMovie(String title)
{
    for (Movie movie : movies){
        if(movie.getTitle().equals(title)){
            movies.remove(movie);
        }
    }
}

There is another class called Movie if anyone needs me to post it. This throws an exception though. Why?

Alessio
  • 3,404
  • 19
  • 35
  • 48
feelingstoned
  • 95
  • 1
  • 10
  • It will throw a `ConcurrentModification Error` as @ScaryWombat said use an iterator – 3kings Mar 01 '16 at 01:54
  • 1
    We can guess that you're getting a [`ConcurrentModificationException`](https://docs.oracle.com/javase/7/docs/api/java/util/ConcurrentModificationException.html), but you should always show the exact error you're getting, instead of just "I get an error", because that's pretty useless to us. – Andreas Mar 01 '16 at 01:55
  • @Andreas yes that is the error i get, sorry about that. – feelingstoned Mar 01 '16 at 01:58

1 Answers1

0

You're trying to remove an element from a list youre looping through so it will throw a concurrent modification exception. There are a number of ways to get around this:

  • use an iterator
  • make a list of to be removed elements and add the elements you wish to remove to it in the loop and then remove all those elements from it afterwards
  • use a for loop not a for each loop accounting for the shift when you remove an element (I.e. i--)
  • loop backwards through the list
  • probably others that I missed

Read solutions from here: How to avoid "ConcurrentModificationException" while removing elements from `ArrayList` while iterating it?

Community
  • 1
  • 1
Hatward
  • 62
  • 7
  • it won't let me iterate since the ArrayList is made from another class and instead gives me `java.util.iterator cannot be converted to java.util.iterator` this is the method i wrote: /** * Write a mehod that removes the movie with a given title */ public void removeMovie(String title) { Iterator itr = movies.iterator(); while (itr.hasNext()){ if(itr.next().equals(title)){ itr.remove(); } } } – feelingstoned Mar 01 '16 at 02:16
  • Change Iterator to Iterator :) – Hatward Mar 01 '16 at 02:19
  • Duh! what was I thinking. Although the method works it doesn't seem to remove anything...I also have a method called `printMovies()` and it still prints the movie I removed – feelingstoned Mar 01 '16 at 03:57