How to use For-Each loop on my own collection?
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.
You need to implement the Iterable<T>
interface so that foreach
will use your iterator.
精彩评论