如何在我自己的集合上使用 For-Each 循环?
我有一个 Network 类,其中 NET
= ArrayList
。 我使用 Network 类来控制可以添加和不能添加的内容,维护 ArrayList 的排序等,我有一个 get 方法,该方法采用节点号作为参数,该方法在 上使用二进制搜索ArrayList
(它们根据该数字排序)
但在大多数情况下,当其他对象需要调用节点时,它们只需要遍历节点,而不管其数字如何,并且通常完全不知道数字。
在 Network
中,我有
public Iterator<Node> iterator() {
return NET.iterator();
}
类似
Iterator<Node> i = net.iterator();
Node n;
while (i.hasNext()) {
n = i.next();
// do stuff
}
But for
for (Node n : net) {
}
我得到的“foreach 不适用于表达式类型”。如果可能的话,我还需要向网络添加什么才能使用 for-each 循环?
我对此的研究只让我找到了解释为什么我需要每个主题的主题,并且我认为它在这种情况下是相关的。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要实现
Iterable;
接口,以便foreach
将使用您的迭代器。You need to implement the
Iterable<T>
interface so thatforeach
will use your iterator.