I am building an app in Android Studio with various tree and shrub preferences and checkboxes. You check a box that indicates you want a tree with a certain trait, and the code runs through an arraylist of all the trees and shrubs in the inventory (I created a Plant class, with attributes like size, name, fruit, etc) and adds all String names of objects that match that criteria to another arraylist of strings to be printed (called 'selections') on a different screen (duplicates are eliminated before printing in another step).
The problem is with removing objects from an arraylist during iteration. Here is a sample:
if (cb_s.isChecked()) {
for(Plant p : test){
if(p.getSize() == "s"){
selection.add(p.getName());
}
else{
selection.remove(p.getName());
test.remove(p);
}
}
}
if (cb_m.isChecked()) {
for(Plant p : test){
if(p.getSize() == "m"){
selection.add(p.getName());
}
else{
selection.remove(p.getName());
test.remove(p);
}
}
}
if (cb_l.isChecked()) {
for(Plant p : test){
if(p.getSize() == "l"){
selection.add(p.getName());
}
else{
selection.remove(p.getName());
test.remove(p);
}
}
}
For every checkbox checked, it runs through an arraylist named 'test' to pick out the plants that correspond to the checkbox (in this case, these three blocks would pick out small, medium, and large plants - s, m, and l) and adds them to another arraylist of strings to be printed later on. It also removes plants from the first arraylist, test, so that they cant be compared if other checkboxes are checked (this would result in a final list of plants that dont meet all criteria selected with checkboxes).
Java doesnt like the way I am trying to remove elements from the arraylist 'test', since that is what I am iterating through. What would be the proper way to remove objects during iteration if they dont meet the criteria? Ive heard that I should use the iterator of the actual collection? How would I go about doing that for this code?
Thanks!