Thomas Mitchell
Thomas Mitchell

Reputation: 1071

Strange Java for loop format

I've come across a for loop structured in a way I've never seen before. I'm wondering if you can explain to me what it is doing? It is provided as one of the examples for verlet integration in Processing:

http://www.openprocessing.org/sketch/17191

Here is the code:

for(VerletParticle2D p : physics.particles) {
    ellipse(p.x, p.y, 5, 5);
}

Is it simply adding an 'p' particle until it reaches the amount that has been setup before?

Upvotes: 1

Views: 1117

Answers (4)

Speckpgh
Speckpgh

Reputation: 3372

The for loop is iterating through the "Particles" in physics.particles and for every element in it, it is calling the ellipse function call.

Upvotes: 3

MarioDS
MarioDS

Reputation: 13063

That is a for-each loop. It iterates over a collection.

In this case, the collection is physics.particles. p will represent the current object in each iteration. VerletParticle2D is the compiler type of the object.

Upvotes: 3

Alain
Alain

Reputation: 27220

This is the Java "For-Each" loop. It iterates over all elements in a collection.

http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html

Upvotes: 3

NPE
NPE

Reputation: 500367

It's the so-called "for each" loop. It simply iterates over all elements of the collection (or array) physics.particles, assigning each element in turn to p.

For further information, see Oracle documentation.

Upvotes: 7

Related Questions