有人能举例说明在Java 5的可迭代接口之前将迭代器添加到自定义类的最佳方法吗?
将包装收藏作为最佳选择吗?像
这样的东西public Iterator iterator() {
return wrappedCollection.iterator();
}
在我的帖子中,我将Iterator与Iterable混淆了。我感兴趣的最终结果是能够使用以下内容对自定义类进行操作。
Iterator it = customClass.iterator();
while (it.hasNext()) {
//do stuff
}
答案 0 :(得分:4)
您是否添加了类似
的方法public Iterator iterator() {
return new YourCustomIterator(...);
}
答案 1 :(得分:4)
如果你只是包装一个集合,你可以使用转发方法。
public class Custom implements Collection {
Collection c; // create an instance here or in the constructor
...
// forwarding method
public Iterator iterator()
{
return c.iterator();
}
}
我认为最好实现你正在包装的任何类型的Collection Interface,而不是Iterator。
答案 2 :(得分:1)
听起来你刚刚在包含Collection的类中添加了这些方法。在这种情况下,您的对象现在也是您的迭代器。您可能要做的是创建一个实现Iterator的新类,并通过iterator()方法使用Collection的克隆进行实例化。
答案 3 :(得分:1)
如果您只想公开内部集合的迭代器,则只返回该集合迭代器。如果你想做更多的事情,你要么必须自己包装,要么查看Apache Commons Collections包,其中包括相当多的迭代器bulider和修改器方法。 (即使你不能使用他们的方法,他们的实现应该教会你很多关于构建迭代器的方法。)
答案 4 :(得分:1)
您希望集合具有迭代器方法,该方法根据需要返回私有Iterator类的实例。
public class IterableTest
{
public Iterator iterator()
{
return new IteratorTest();
}
private class IteratorTest implements Iterator
{
public boolean hasNext(){...}
public Object next(){...}
public void remove(){...}
}
}
答案 5 :(得分:1)
我猜您正在寻找类似下面的内容
http://karephul.blogspot.com/2009/05/concurrentmodificationexception.html
&安培;是的,内心阶级的想法就是你要找的。 p>