0

I have two ObservableList which one of them contains some song and other one has the directory that related to songs.

I want when remove a directory from its ObservableList, all of the songs those contain that directory be removed from their ObservableList. but when I do that, just songs with odd id removed and ones with even id remained !!!

my ObservableLists are in a different class and "controller" is the object of the class that contains the ObservableLists. here is my code :

private static ObservableList<SongModel> songModelObservableList = FXCollections.observableArrayList();
private static ObservableList<Directory_Model> directoryModelObservableList = FXCollections.observableArrayList();

and now my code that remove directory :

for (int j = 0 ; j < controller.getSongModelObservableList().size() ; j++)
   if (controller.getSongModelObservableList().get(j).getPath().contains(controller.getDirectoryModelObservableList().get(i).getPath())){
         controller.getSongModelObservableList().remove(controller.getSongModelObservableList().get(j));

          }
    controller.getDirectoryModelObservableList().remove(controller.getDirectoryModelObservableList().get(i));

here. in the first if, I check which songModel(my class for songs) has the directory's path to remove it from songObservableList.

have any idea to fix that? I want to remove all of directory's songs not ones with odd id.

AliXo
  • 21
  • 4
  • I believe when you remove an item from a list, the list collapses to fill in the void. So your indexes will be out of whack. – trilogy Dec 23 '18 at 14:47
  • Possible duplicate of [Remove elements from collection while iterating](https://stackoverflow.com/questions/10431981/remove-elements-from-collection-while-iterating) – Slaw Dec 23 '18 at 15:05

1 Answers1

1

If you remove the element at index j from the list, the item at position j after modification is the item that was previously at index j+1. Since you increment the index after every iteration of the loop, you skip an item, if you remove one in the iteration. Instead only increment the index, if no item is removed:

final String removePath = controller.getDirectoryModelObservableList().get(i).getPath();
for (int j = 0; j < controller.getSongModelObservableList().size();)
   if (controller.getSongModelObservableList().get(j).getPath().contains(removePath)){
       controller.getSongModelObservableList().remove(j);
   } else {
       j++;
   }
}
controller.getDirectoryModelObservableList().remove(i);

It would be simpler though to simply use a Predicate with removeIf:

final String removePath = controller.getDirectoryModelObservableList().get(i).getPath();
controller.getSongModelObservableList().removeIf(element -> element.getPath().contains(removePath));
fabian
  • 80,457
  • 12
  • 86
  • 114