[英]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.