Question

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).

Was it helpful?

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.

OTHER TIPS

This code is of little use

  for(Object obj : myArrayList) {
    // You're checking again and agian the condition that's loop independent
    if(myArrayList.contains(someParticularData)){
      continue;
    }
   //do something
  }

A more effective implementation is (check whether you need the loop at all first)

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

continue is convenient in conditions like that:

  for(Object obj : myArrayList) {
    // Check for each item: do we need to proceed this item
    if (someArrayList.contains(obj))
      continue;

    //do something
  }

Whenever you are looping on some value range, you are processing on each of the value comes between the initial and final one...

For example if you are making addition of odd numbers. it is convenient to use loop which will be incremented by 2 rather than continuing for each odd value,

for (int i = 0; i < 100 ; i=i+2){
   // do addition
}

but if you are modifying your value that is being checked within the loop, than continue or break is good practice to implement.

for example,

boolean flag = false;
// flag will be modified in some iteration of loop, but you don't know which.
for ( int i = 0 ; i < 100 ; i++ ) {
   if ( flag ) {
      continue;
   }
   // flag modified somewhere..
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top