开发者

Java doing a For loop but also using an iterator for Linked List ( "For, While") Loop?

开发者 https://www.devze.com 2023-02-15 05:22 出处:网络
I apologize for the basic question but my newness to Java is causing me some frustration and I am unable to find an elegant way to do this from my searches.

I apologize for the basic question but my newness to Java is causing me some frustration and I am unable to find an elegant way to do this from my searches.

I want to iterate through a linked list using a For construct but also have an numerical iterator so that I can break the loop after a certain number of iterations.

I have this LL that I am iterating through:

LinkedList<SearchResult> docSearch开发者_如何学编程;

I tried doing it like this but then only the iterator part worked (the result was always stuck on the first entry for each iteration)

for (SearchResult result : docSearch) while (iter2 < 50)  { 

//do stuff
iter2 = iter2 + 1;
}

Any advice is appreciated


If you have to do that sort of checking, then I would just do it with an if in the block.

for (SearchResult result : docSearch)  {
  if (iter2 >= 50) break;

  //do stuff
  iter2 += 1;
}


It will be better to use regular for..loop syntax to handle your need

for (int i = 0; i < 50 && i < docSearch.getSize(); i++ ) {
    SearchResult result = docSearch.get(i);
}

Just because Java support for-each loop, does not mean we have to use it every time. I find using regular for..loop syntax is easier to read where your condition is isolated in 1 place. If you use for-each with break then you have 2 places which affect your code flow.


where did you assign the value of iter2?

try

for (SearchResult result : docSearch) 
{
  int iter2 = 0;
  while (iter2 < 50)  { 

  //do stuff
  iter2 = iter2 + 1;
  }
}


for (SearchResult result : docSearch)  {
  if (iter2++ >= 50) break;
  //do stuff
}

Here might be a nice place for a post-incrementation too. :)


If you do this:

for (SearchResult result : docSearch) while (iter2 < 50)  { 

//do stuff
iter2 = iter2 + 1;
}

It's the exact same as doing this:

for (SearchResult result : docSearch) {

    while (iter2 < 50)  { 

    //do stuff
    iter2 = iter2 + 1;
    }
}

You can get around this in a number of ways. One is a break (although some frown upon this as spaghetti code.

for (SearchResult result : docSearch) { 
if(iter2 >= 50) break;
//do stuff
iter2 = iter2 + 1;
}

You can use a standard for loop and put the two conditions into the condition section

Iterator<SearchResult> iter = docSearch.iterator();
for(SearchResult result = iter.next(); iter.hasNext() && iter2 < 50; result = iter.next()) {
   // do stuff
   iter2 = iter2 + 1;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消