是否可以在Java中扩展迭代器的function?

我想知道是否有一种方法来扩展迭代器接口的function。 假设我们有一个实现Iterable接口的Class(在上面的例子中,我没有添加myFunction的Iterator接口的重写函数)。

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(){ } }; } } 

如果我把这个代码放在另一个函数中我得到编译错误(“找不到符号”),我想知道为什么会发生这种情况。

 public void anotherFunction(){ MyClass a = new MyClass(); a.iterator().myFunction(); } 

当然是。 您可以创建另一个界面:

 interface MyBetterIterator extends Iterator { void myFunction(); } 

然后让方法返回你的类型:

 public class MyClass implements Iterable{ @Override public MyBetterIterator iterator() { ... } } 

该function称为“返回类型协方差”,在Java 5中引入。

即使你已经将自己的函数添加到Iterator实例中,但是你告诉所有使用你的类的类是你要返回一个Iterator 。 这意味着您仅限于Iterator接口公开的签名。 如果你想访问myFunction,你必须正式声明你自己的扩展Iterator的接口,然后让你的iterator()函数返回。 但是,这也将破坏Iterable合同,因此您必须做出选择。

您的myFunction()不属于Iterator接口,因此不能在使用Iterator类型声明的Object上使用。

 a.iterator().myFunction(); ^ Returns an Iterator and therefore gives a compilation error