user2644819
user2644819

Reputation: 1837

Iteration through data structures(queue, stacks, bags)

Queue<Transaction> collection = new Queue<Transaction>

and

for(Transaction t: collection)
{ StdOut.println(t); }

From my understanding of objects, it looks like we just created an object, the queue, of datatype transaction(type parameter) and collection is the reference to that object. Correct?

Then the second bit of code is what confuses me. We are looping to print whats in the queue but i'm not sure i understand how this works. collection points to the Queue of type Transaction. It looks like we are creating a reference t to the object Transaction and doing something with it to the reference collection. Pretty confused.

Upvotes: 0

Views: 2326

Answers (5)

See http://docs.oracle.com/javase/7/docs/api/java/util/Queue.html. Queue is part of the Java Collection Framework and therefore implements the Iterable interface. The for-each shortcut uses that fact and utilise the Iterator object that Queue produces to iterate over all elements. It's equivalent to:

Iterator<Transaction> I = collection.iterator();
for(;;I.hasNext()) {
  Transaction t = I.next();
  StdOut.println(t);
}

Upvotes: 1

OldCurmudgeon
OldCurmudgeon

Reputation: 65889

For for(Transaction t: collection) read:

For each Transaction in collection

or

For Transaction t over collection.

Upvotes: 0

tbodt
tbodt

Reputation: 17017

The "for-each" notation is actually replaced by this in the final class file:

for(Iterator i = collection.iterator(); iterator.hasNext(); Transaction t = iterator.next())

This just obtains an iterator and sets t equal to the next value of the iterator each time through the loop. This can be done with any object that implements Iterable.

Upvotes: 2

bas
bas

Reputation: 1678

What is happening here is that the Queue has an iterator() method. When you feed it to a foreach-loop like you are doing here, you are calling an iterator-object. Next the for-loop starts iterating through the objects in that iterator.

Upvotes: 1

Avi
Avi

Reputation: 21866

This is syntactic sugar that java has for dealing with iterators. Queue implements the Iterable interface. The for loop asks for the collection's iterator and knows how to handle it.

For each class that implements Iterable you can use this syntax.

Upvotes: 2

Related Questions