是否可以在Java中扩展迭代器的功能? [英] Is it possible to extend the functionality of an iterator in Java?
问题描述
我想知道是否有办法扩展迭代器接口的功能。假设我们有一个实现Iterable接口的Class(在上面的例子中,我没有添加myFunction的Iterator接口的重写函数)。
I was wondering if there is a way to extend the functionality of the iterator interface. Suppose that we have a Class that implements the Iterable interface (in the example above, instead of the overridden functions of the Iterator interface I have added myFunction).
public class MyClass implements Iterable{
@Override
public Iterator iterator() {
return new Iterator() {
@Override
public boolean hasNext() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Tuple next() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void remove() {
throw new UnsupportedOperationException("Not supported yet.");
}
public void myFunction(){
}
};
}
}
如果我将此代码放在另一个函数中,我会得到编译错误(找不到符号),我想知道为什么会发生这种情况。
If I put this code in another function I get compilation error ("cannot find symbol") and I was wondering why this happens.
public void anotherFunction(){
MyClass a = new MyClass();
a.iterator().myFunction();
}
推荐答案
是的,当然。您可以创建另一个界面:
Yes, of course. You could create another interface:
interface MyBetterIterator extends Iterator
{
void myFunction();
}
然后让方法返回你的类型:
then make the method return your type:
public class MyClass implements Iterable{
@Override
public MyBetterIterator iterator() {
...
}
}
此功能称为返回类型协方差,在Java 5。
The feature is called "return type covariance", introduced in Java 5.
这篇关于是否可以在Java中扩展迭代器的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!