I came across some Java syntax that I haven't seen before. I was wondering if someone could tell me what's going on here.
for (ObjectType objectName : collectionName.getObjects())
It's called a for-each or enhanced for statement. See the JLS §14.14.2.
for
It's syntactic sugar provided by the compiler for iterating over Iterables and arrays. The following are equivalent ways to iterate over a list:
Iterable
List<Foo> foos = ...; for (Foo foo : foos) { foo.bar(); } // equivalent to: List<Foo> foos = ...; for (Iterator<Foo> iter = foos.iterator(); iter.hasNext();) { Foo foo = iter.next(); foo.bar(); }
and these are two equivalent ways to iterate over an array:
int[] nums = ...; for (int num : nums) { System.out.println(num); } // equivalent to: int[] nums = ...; for (int i=0; i<nums.length; i++) { int num = nums[i]; System.out.println(num); }
1.4m articles
1.4m replys
5 comments
57.0k users