I have an ArrayList that contains instances of the Staff class. When I write the following code I am told by IntelliJ that the 'for statement does not loop':
public String getTypist() {
String tempTy = "";
for (Staff g : staffList) {
if (g.getStaffID().contains("TY") && g.isAvailable()){
tempTy = g.getStaffID();
}
staffList.remove(g);
staffWorking.add(g);
break;
}
return tempTy;
}
I'm really confused as I thought that this was the way to properly use a for loop on an ArrayList. What am I doing incorrectly with my for loop?
Your
forloop contains abreakstatement which always executes no matter what happens before in the loop, so after the very first looping occurs, thebreakhappens, and nothing else is looped afterwards. This basically makes it as though there was noforloop at all, as executing code one time is the default way a series of statements are executed. Correcting this involves making sure thebreakexecutes only some of the loops (specifically, making sure it only executes on the loop you want to be the last loop). Making that correction with the addition of some other fixes you would get code similar to this:However, there is an alternative solution that would allow you to avoid iterating over the
ArrayListat all. You can replace that code with this code and it will work without anyforloop because it uses the methods of theArrayListitself to accomplish the task:Though even that could be simplified and improved to this (this code supports concurrent filtering so on multi-processor systems it will be much faster):