简体   繁体   中英

java compiler error with generics and an iterator

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.

Here,

public class MyList<Integer> extends ArrayList<Integer> {
                //  ^ here

you are declaring a type variable Integer which shadows the java.lang.Integer type.

Anywhere within the type body where you refer to Integer , you are referring to the type variable rather than the java.lang.Integer type.

The various numerical operators do not apply to random types (which is what your type variable is), they only work with primitive numeric types and their wrapper classes. Therefore you can't use them with operands of the type of your type variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM