0

could someone please explain how the enhanced for loop in the code below would look if it was represented by a standard for loop? ex for(int loop = 0; loop < ____; loop++) etc. I am trying to understand what the enhanced for loop does but want to see how it is represented in a standard for loop.

public static void main(String[] args) {
    // get the list of each winning team by year
    ArrayList<String> allWinners = readAndPopulateWinnersList();
    int startYear = 1956;
    for(String teams : allWinners) {
        System.out.println(startYear++ + " : " + teams);
    }
    
    }
bigdog123
  • 11
  • 4

1 Answers1

1

If you want to change your for(String teams: allWinners) to standard loop here it is:

for (int i = 0; i < allWinners.size(); i++) {
    System.out.println(startYear++ + " : " + allWinners.get(i));
}

In for each you have simply form without .get(i) etc. but you don't have index either.

So If you want to print allWinners item with its index then standard for loop will be better for you. You can also use Java Streams APi: https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html

so it will be allWinners.forEach(element -> System.out.println(startYear++ + " : " + element));

MrFisherman
  • 720
  • 1
  • 7
  • 27
  • Thanks a lot! it was the allWinners.get(i) that i needed. much appreciated! – bigdog123 Jan 05 '21 at 14:53
  • It may be worht mentioning that enhanced for-loop will work better with LinkedList because it avoids `get(index)` which would for each call need to start from beginning of list making it `O(N)` operation and N series of `O(N)` would be `O(N^2)`. To avoid this problem enhanced for-loop is using Iterator provided by list. So in case of LinkedList it will remember current Node and will simply need to jump to next Node. – Pshemo Jan 05 '21 at 14:58