Lucía
Lucía

Reputation: 91

I don't understand a condition in a loop

I am reading some code in Java and I don't understand the condition of this loop:

for (Integer label : labelConj) 
{...........
}

"label" is an integer and "labelConj", a set of integers. What does the condition control? I can't find any information in Java tutorials. Thanks in advance.

Upvotes: 3

Views: 176

Answers (7)

dlev
dlev

Reputation: 48596

It's not a condition, it's a foreach loop. It's saying "for each Integer (which will be called label inside the loop body) in the collection of Integers called labelConj, loop." The loop will execute once for each item, and then stop.

This syntax can be used with most of the collection classes in the Java framework, and classes you write can use it if you either inherit from one of those classes, or implement the Iterable interface.

Upvotes: 11

Monis Iqbal
Monis Iqbal

Reputation: 2037

This is the same as:

for (int i=0; i<labelConj.length; i++) {
    Integer label = labelConj[i];
    ...
}

Upvotes: 1

perissf
perissf

Reputation: 16273

This is a compact form of the for loop (called Enhanced For statement) which loops for all the elements in an array and assigns each element to a given variable (in this case, "label"). See here for ref: http://download.oracle.com/javase/tutorial/java/nutsandbolts/for.html

Upvotes: 0

Andrew Fielden
Andrew Fielden

Reputation: 3899

It's a shorthand way of iterating over a collection of things. Here's a link to some information. Just Google 'enhanced for loop'

http://blogs.oracle.com/CoreJavaTechTips/entry/using_enhanced_for_loops_with

Upvotes: 0

ennuikiller
ennuikiller

Reputation: 46965

this is a fast enumeration equivalent to for (Integer label in labelConj)

Upvotes: 0

amit
amit

Reputation: 178461

it is a foreach loop. It iterates over all elements (Integers in your example) in labelConj.

Upvotes: 4

nyanev
nyanev

Reputation: 11519

This iterate through the List of integers. This is foreach loop in PHP

Upvotes: 0

Related Questions