user2580777
user2580777

Reputation: 79

A for loop using colons

I'm studying code and I don't understand what the for loop is actually doing.

for (final Move move : this.getPossibleMoves(color)) { 
      // do something..
}

Class Move:

public class Move {
private final int source;
private final int target;

public Move() {
    source = 0;
    target = 0;
}

getPossibleMoves method:

public Move[] getPossibleMoves(final PieceColor color) {
    // do something
    return simpleMoves.toArray(new Move[0]);
}

Upvotes: 1

Views: 188

Answers (3)

Maroun
Maroun

Reputation: 95978

See the official docs on the For-Each Loop for explanation.

You can think about it this way:

for (Iterator<Move> itr = this.getPossibleMoves(color).iterator(); itr.hasNext();)
{
   final Move mv = itr.next();
   ...
} 

Upvotes: 2

AllTooSir
AllTooSir

Reputation: 49402

That is an enhanced for loop, introduced with the Java SE platform in version 5.0, It is a simpler way of iterating over the elements of an array or Collection. They can be used when you wish to step through each element of the array in first-to-last order, and you do not need to know the index of the current element.

Assuming this.getPossibleMoves(color) returns a Move[] array.This code :

for (final Move move : this.getPossibleMoves(color)) { 
   // do something....
}

is implicitly equivalent to :

for (int index=0;index<this.getPossibleMoves(color).length;index++) { 
    final Move move = this.getPossibleMoves(color)[index];
   // do something....
}

Suggested Reading:

  1. The For-Each Loop.
  2. Using Enhanced For-Loops
  3. Enhanced for each loop iteration control

Upvotes: 0

morgano
morgano

Reputation: 17422

This for statement has this form:

form(Type element: iterable) { ... }

where element is an element of an array, list, set or any collection of objects that are contained in an object of type Iterable.

in your case getPossibleMoves() is returning an array of objects of type Move. This is your code in a clearer way so you understand better what it does:

Move[] moves = this.getPossibleMoves(color);


for (final Move move : moves) { 

    // do something....

}

Upvotes: 1

Related Questions