I have the following code (Yes, I know the iterator is implemented incorrectly. This is an exam question I'm writing):
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);
}
}
}
When I compile, it won't auto box the Integer for modulo op, and I get
MyList.java:9: error: bad operand types for binary operator '%'
if (iter.next() % 2 == 1)
first type: Integer
second type: int
If I change iter.next()
to iter.next().intValue()
, I get
MyList.java:9: error: cannot find symbol
if (iter.next().intValue() % 2 == 1)
symbol: method intValue()
location: class Object
However, if I change
public class MyList<Integer>...
to
public class MyList
then the errors go away.
Thoughts on what's going on?
Thanks.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…