我正在编写一个实现迭代器的内部类,我正在尝试为我的一个方法返回一个整数,但它不允许我。我知道这是一个非常基本的问题,但我是 java 的新手,所以我很抱歉它听起来很简单。
public class pIterator<Integer> implements Iterator<Integer>{
private int currentEx = 1;
private int base = 4;
//error says can't convert int to Integer here specifically
private Integer changeToInteger = base * currentEx++;
@Override
public boolean hasNext() {
return currentEx <= max;
}
//the problem then occurs here when I try to return an Integer
@Override
public Integer next() throws NoSuchElementException {
if (currentEx > max) throw new NoSuchElementException();
return changeToInteger;
}
}
currentEx 和 base 必须是整数(由指令定义(,所以我应该只更改返回类型还是可以转换为整数?
通过将
类定义为具有名为 Integer 的参数的泛型类来隐藏标准java.lang.Integer
。它应该定义为
public class pIterator implements Iterator<Integer> {
否则,您的类相当于
public class pIterator<T> implements Iterator<T> {
但T
令人困惑地命名为Integer
.