0

I want to remove an instance of an ArrayList, but with the code I have now it lists the movies removed. I have an ArrayList that takes title, year, genre and balance. The goal is to remove from the list using only title and year.

I have tried a for-each loop, but that leads to ConcurrentModificationException error, and I am not sure how use use Iterators to make it work for this example.

It is supposed to remove the instance specified by title and year so that when it lists the moviesAvailable, the list would be updated. However when listing it shows all movies (probably because it is not actually removing the movie).

T Dizzle
  • 69
  • 7
  • 1
    If you do not override `equals` on your Movie class how can anything tell that one instance equals another? – Scary Wombat May 08 '19 at 01:53
  • Possible duplicate of [Calling remove in foreach loop in Java](https://stackoverflow.com/questions/1196586/calling-remove-in-foreach-loop-in-java) – qtopierw May 08 '19 at 01:55
  • See https://stackoverflow.com/questions/1196586/calling-remove-in-foreach-loop-in-java, or use index in for-loop to remove the item. You should not use for-each to remove elements see https://docs.oracle.com/javase/8/docs/technotes/guides/language/foreach.html – qtopierw May 08 '19 at 01:58
  • How would I go about using an iterator in this case? – T Dizzle May 08 '19 at 04:11

2 Answers2

1

One way to remove the targeted movie is via the Collections.removeIf() method:

public void removeMovie() {
    System.out.println("\nRemoving a movie.");
    System.out.print("Enter the title of the movie: ");
    String title = In.nextLine();
    System.out.print("Enter the year: ");
    int year = In.nextInt();
    moviesAvailable.removeIf(movie -> movie.hasType(title, year));
    // other stuff...
}

Note

  • The removeIf method iterates through your collection and true to its name, removes an element (a movie in this case) which satisfy the condition.
  • If your entry was not deleted, please check to see if title and year are correct. For example, does title contain a trailing new line?
Hai Vu
  • 37,849
  • 11
  • 66
  • 93
0

you can do something like

 moviesAvailable.removeIf(m -> m.hasType("s",2));
jlco
  • 1