How do forach iterations work in Java?

Asked 1 years ago, Updated 1 years ago, 87 views

List<String> someList = new ArrayList<String>();
// // add "monkey", "donkey", "skeleton key" to someList
for (String item : someList) {
    System.out.println(item);
}

Can I define the same thing using a for statement instead of a forach statement?

syntactic-sugar java foreach

2022-09-22 21:42

1 Answers

for(Iterator<String> i = someList.iterator(); i.hasNext(); ) {
    String item = i.next();
    System.out.println(item);
}

If you use i.remove(); in a repeating statement or if you want to access the actual iterator, you cannot use the for(:) command statement.

This source code is operational for any object that implements Iterable interface.

Also, if the right input in the for(:) statement is array instead of Itaerable object, the internal source code uses an int-type index counter to check array.length. Check out Java spec.


2022-09-22 21:42

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.