Search code examples
javaloopscontinue

Alternative for 'continue' keyword


I was browsing through questions regarding continue keyword to get a better understanding of it and I stumbled upon this line in this answer

These can be maintenance timebombs because there is no immediate link between the "continue"/"break" and the loop it is continuing/breaking other than context;

I have this for loop:

for(Object obj : myArrayList){
  if(myArrayList.contains(someParticularData)){
       continue;
    }
   //do something
}

Now, my question is - Is it okay to use continue in the manner that I have done above or does it have any issues? If yes, what is the alternative approach that I can follow? Any kind of guidance would help. Thank you.

Update: My objective in this particular situation would be to iterate over a Collection ( ArrayList, in this case), and check if that contains some particular data and skip that iteration if it is true. I was pointed out that myArrayList.contains(someParticularData) is a one time operation and that it would be better off to perform that check outside the loop, which is what I was looking for. Also, I learnt that if I can use continue based on some condition if(someConditon), I can very well avoid it by using if(!someCondition).


Solution

  • for(Object obj : myArrayList){
        if(someCondition){
           continue;
        }
        //do something 
    }
    

    can be replaced with:

    for(Object obj : myArrayList){
        if(!someCondition){
           //do something 
        }
    }
    

    IMHO, as far as you don't have a lot (like 2-3 continue/break/return), maintenance will be fine.