在java中嵌套的foreach语句 [英] nested foreach statement in java
问题描述
是否有可能在java中嵌入foreach语句,并在外部foreach循环所在的当前索引处启动嵌套语句? 所以如果我有 p>
List< myObj> myObjList = new ArrayList< myObj>();
(myObj o:myObjList){
//如何在列表中的当前位置启动嵌套for循环?
$(
)
谢谢!
这是通过自己跟踪索引来实现的,然后使用 subList
开始内部循环:
pre code $ int $ i
(myObj o1:myObjList ){
for(myObj o2:myObjList.subList(i,myObjList.size())){
//做某事
}
i ++;
}
我认为这比使用基本
但是,这两者都应该工作,所以选择是你的。请注意,如果你使用的集合没有实现 List< E>
,这个在 List< E>
上定义了 subList
,因为索引的概念确实只有意义列表)。
Is it possible to nest foreach statements in java and start the nested statement at the current index that the outer foreach loop is at?
So if I have
List<myObj> myObjList = new ArrayList<myObj>();
for (myObj o : myObjList){
// how do I start the nested for loop at the current spot in the list?
for(
}
Thanks!
Here's a way to do it by keeping track of the index yourself, then using subList
to start the inner loop at the right spot:
int i = 0;
for (myObj o1 : myObjList) {
for (myObj o2 : myObjList.subList(i, myObjList.size())) {
// do something
}
i++;
}
I think this is clearer than using basic for
loops, but that's certainly debatable. However, both should work, so the choice is yours. Note that if you are using a collection that does not implement List<E>
, this will not work (subList
is defined on List<E>
as the idea of an "index" really only makes sense for lists).
这篇关于在java中嵌套的foreach语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!