[英]Generic for-loop: Is there a way to get iteration information?
I am used to implement loops with generics like that: 我习惯用这样的泛型实现循环:
for (final Dog lDog : lAllDog) {
...
}
Unfortunality for another business case I need the current count of the iteration. 对于另一个业务案例的不幸,我需要迭代的当前计数。 I know I can solve this by coding somthing like that:
我知道我可以通过编写类似的东西来解决这个问题:
for (int i = 0 ; i < lAllDog.length(); i++) {
System.out.println(i);
}
or 要么
int i = 0;
for (final Dog lDog : lAllDog) {
...
i++;
}
but is there a way to get the current count of iteration with my first code example without declaring a new int
or change the whole loop header? 但有没有办法用我的第一个代码示例获取当前的迭代计数而不声明一个新的
int
或更改整个循环头?
Thx a lot 多谢
Briefly, no. 简而言之,没有。 You have to use the indexing method to do that.
您必须使用索引方法来执行此操作。
No, there is no other to get count of iteration other than you described in your question. 不,除了您在问题中描述的迭代之外,没有其他方法可以获得迭代次数。 You'll have to use old way to have counter defined
你必须使用旧方法来定义计数器
No, if your list has unique elements 不,如果您的列表具有唯一元素
May be you can try this 也许你可以试试这个
for (final Dog lDog : lAllDog) {
int i= lAllDog.indexOf(lDog);
}
They say every problem in computer science can be solved by more indirection 他们说计算机科学中的每个问题都可以通过更多的间接来解决
class Indexed<T>
int index;
T value;
static <T> Iterable<Indexed<T>> indexed(Iterable<T> iterable){ ... }
for(Indexed<Dog> idog : indexed(dogs))
print(idog.index);
print(idog.value);
In java 8, we probably want to abstract this control pattern as 在java 8中,我们可能希望将此控件模式抽象为
forEach(dogs, (index, dog)->{
print(index);
print(dog);
});
static <T> void forEach(Iterable<T> collections, Acceptor<T> acceptor){...}
interface Acceptor<T>
void accept(int index, T value);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.