[英]java compiler error with generics and an iterator
我有以下代码(是的,我知道迭代器实现不正确。这是我正在编写的考试题目):
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:错误:二元运算符'%'的错误操作数类型if(iter.next()%2 == 1)
第一种:整数
第二种类型:int
如果我将iter.next()
更改为iter.next().intValue()
,我得到
MyList.java:9:错误:找不到符号if(iter.next()。intValue()%2 == 1)
符号:方法intValue()
location:类Object
但是,如果我改变了
public class MyList<Integer>...
至
public class MyList
然后错误就消失了。
关于发生了什么的想法?
谢谢。
这里,
public class MyList<Integer> extends ArrayList<Integer> {
// ^ here
您正在声明一个类型变量Integer
,它会影响java.lang.Integer
类型。
在您引用Integer
的类型主体中的任何位置,您指的是类型变量而不是java.lang.Integer
类型。
各种数值运算符不适用于随机类型(这是您的类型变量),它们只适用于原始数字类型及其包装类。 因此,您不能将它们与类型变量类型的操作数一起使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.