Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
215 views
in Technique[技术] by (71.8m points)

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...