Reputation: 988
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!
Upvotes: 3
Views: 13813
Reputation: 56586
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).
Upvotes: 6
Reputation: 159874
No. Enhanced for
loops conceal the current index of the loop. You need to use a basic for loop which uses an index.
Upvotes: 6
Reputation: 8463
While you could do something like this, it would be extremely sub-optimal. Consider that the indexOf
method would be iterating across the entire list (again!) to find the object. Note also that it depends on myObjList being an ordered collection (list):
List<myObj> myObjList = new ArrayList<myObj>();
for (myObj o : myObjList){
int idx = myObjList.indexOf(o);
for(myObj blah : myObjList.subList(idx, myObjList.size()) {
...
}
}
far better:
int myObjListSize = myObjList.size();
for (int outerIndex = 0; outerIndex < myObjListSize ; outerIndex++){
for(int innerIndex = outerIndex; innerIndex < myObjListSize ; innerIndex++) {
myObj o = myObjList.get(innerIndex);
}
}
other note: class myObj
should be capitalized to class MyObj
to adhere to Java naming standards
Upvotes: 1