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
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.
© 2024 OneMinuteCode. All rights reserved.