我有以下代码(是的,我知道迭代器的实现不正确。这是我正在编写的考试问题):
public class MyList<Integer> extends ArrayList<Integer> {
public void noOdds() {
MyIterator<Integer> iter = this.iterator();
while (iter.hasNext()) {
if (iter.next() % 2 == 1)
iter.remove();
}
}
public MyIterator<Integer> iterator() {
return new MyIterator<Integer>(this);
}
public class MyIterator<Integer> implements Iterator<Integer> {
List<Integer> data;
int size;
int position;
MyIterator(List<Integer> data) {
this.data = data;
this.size = data.size();
this.position = 0;
}
public boolean hasNext() {
if (this.position < this.size)
return true;
else
return false;
}
public Integer next() {
Integer tmp = this.data.get(this.position);
this.position++;
return tmp;
}
public void remove() {
if (this.position == 0)
throw new IllegalStateException("next hasn't been called yet");
this.data.remove(this.position - 1);
}
}
}
当我编译时,它不会自动将Integer装箱以进行模运算,然后我得到
MyList.java:9:错误:如果(iter.next()%2 == 1),二进制运算符'%'的操作数类型错误
第一种类型:整数
第二种类型:int
如果我更改iter.next()
为iter.next().intValue()
,我得到
MyList.java:9:错误:如果(iter.next()。intValue()%2 == 1)找不到符号
符号:方法intValue()
位置:类Object
但是,如果我改变
public class MyList<Integer>...
到
public class MyList
然后错误消失了。
对正在发生的事情有什么想法?
谢谢。
这里,
public class MyList<Integer> extends ArrayList<Integer> {
// ^ here
您正在声明一个Integer
遮盖该java.lang.Integer
类型的类型变量。
在您引用的类型主体内的任何位置Integer
,您引用的是类型变量,而不是java.lang.Integer
类型。
各种数值运算符不适用于随机类型(这是您的类型变量),它们仅适用于原始数值类型及其包装器类。因此,不能将它们与类型变量类型的操作数一起使用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句