无法通过迭代器实现next()方法

use*_*664 -1 java interface

我试图通过接口实现next()方法,但它给了我一个错误.这是我有的:

private class MyIterator implements Iterator<Term>
{

    private final Polynomial myArray;
    private int current;

    MyIterator(Polynomial myArray) {
        this.myArray = myArray;
        this.current = myArray.degree;
    }

    @Override
    public boolean hasNext() {
        return current < myArray.degree;
    }


    @Override
    public Integer next() { //this method right here does not work
        if (! hasNext())   throw new UnsupportedOperationException();;
        return myArray.coeff[current++];
    }

    @Override
    public void remove() {
        throw new UnsupportedOperationException();
    }
}
Run Code Online (Sandbox Code Playgroud)

next()方法然后抛出这个错误:

错误

这是我的界面:

public interface Term {

int coeff();
int exp();
String toString();
}
Run Code Online (Sandbox Code Playgroud)

所以我的问题是为什么接口不允许MyIterator实现next()方法

小智 5

你的班级正在实施Iterator<Term>,所以next()必须返回一个Term,而不是一个Integer.

编辑:这一行

if (! hasNext())   throw new UnsupportedOperationException();;
Run Code Online (Sandbox Code Playgroud)

是错的.如果Iterator没有更多的物品,next()必须抛出一个NoSuchElementException.