0

I have a Network class, in it NET = ArrayList<Node>. I'm using the Network class to control what can and cannot be added, maintaining the ArrayList sorted etc, I have a get method that takes a Node number as argument that uses binary search over the ArrayList (they're sorted according to that number)

But in most cases when other objects need to call on a node they just need to go through the nodes regardless of their numbers and often not knowing the number altogether.

In Network i have

public Iterator<Node> iterator() {
        return NET.iterator();
}

And things like

Iterator<Node> i = net.iterator();
Node n;
while (i.hasNext()) {
    n = i.next();
    // do stuff
}

But for

for (Node n : net) {

}

I get "foreach not applicable to expression type". What else I need to add to Network to use the for-each loop, if possible?

My research on this led me only to topics explaining why would I need a for each, and I think it's relevant in this case.

Recct
  • 913
  • 1
  • 16
  • 40

1 Answers1

8

You need to implement the Iterable<T> interface so that foreach will use your iterator.

Adrian Cox
  • 6,204
  • 5
  • 41
  • 68
  • I see, worked, though at first i was caught in a trap: http://stackoverflow.com/questions/601658/java-how-to-implement-iterable – Recct Feb 26 '11 at 18:05