-2

I'm really new to Java, and was wondering if someone could help me convert the following to foreach loops into for loops?

Assuming expression is a collection of items:

for(Type x: expression){
   ...
   for(Type y: x.expression){
     .....
    }
}
TestNInja
  • 177
  • 2
  • 15

1 Answers1

0

expression needs to be some kind of collection of items. The for (Type item : items) loop just iterates over all of them.

To manually loop over the collection you just need the length of the collection and can use:

for (int i = 0; i < collection.size(); i++) { // or .length() if it is an array
  Type item = collection.get(i); // or collection[i] if it is an array
}

Type needs to be the type of the items in the collection.

schrej
  • 450
  • 3
  • 10
  • How would having a nested foreach loop work in this case? – TestNInja Jun 06 '17 at 00:09
  • 1
    Well just nest them. If `Type` is another collection it will work the same way. Just use something other than `i` (e.g. `j`) for the nested loop or it'll get overwritten. – schrej Jun 06 '17 at 00:09
  • 1
    An enhanced `for` statement does *not* get translated by the compiler to a `for` loop with index variable, because that will not perform for non-array based lists, and don't even work for other types of collections, because they don't have a `get(int)` method. – Andreas Jun 06 '17 at 00:17