Java 执行 For 循环,但也使用迭代器进行链接列表(“For,While”)循环?
我对这个基本问题表示歉意,但我对 Java 的陌生让我有些沮丧,而且我无法从搜索中找到一种优雅的方法来做到这一点。
我想使用 For 构造来迭代链表,但也有一个数字迭代器,以便我可以在一定次数的迭代后中断循环。
我有一个正在迭代的 LL:
LinkedList<SearchResult> docSearch;
我尝试这样做,但只有迭代器部分起作用(结果总是卡在每次迭代的第一个条目上)
for (SearchResult result : docSearch) while (iter2 < 50) {
//do stuff
iter2 = iter2 + 1;
}
任何建议表示赞赏
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您必须进行此类检查,那么我只需在块中使用 if 即可。
If you have to do that sort of checking, then I would just do it with an if in the block.
最好使用常规的 for..loop 语法来满足您的需求
仅仅因为 Java 支持 for-each 循环,并不意味着我们每次都必须使用它。我发现使用常规的 for..loop 语法更容易阅读,因为您的条件被隔离在一处。如果您将 for-each 与break一起使用,那么您有两个地方会影响您的代码流程。
It will be better to use regular for..loop syntax to handle your need
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.
你把iter2的值赋到哪里了?
尝试
where did you assign the value of iter2?
try
这里也可能是进行后增量的好地方。 :)
Here might be a nice place for a post-incrementation too. :)
如果您这样做:
与这样做完全相同:
您可以通过多种方式解决此问题。一个是中断(尽管有些人不同意这是意大利面条代码。
您可以使用标准 for 循环并将两个条件放入条件部分
If you do this:
It's the exact same as doing this:
You can get around this in a number of ways. One is a break (although some frown upon this as spaghetti code.
You can use a standard for loop and put the two conditions into the condition section