简体   繁体   English

带有泛型和迭代器的java编译器错误

[英]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 当我编译时,它不会自动为模数操作选择Integer,我得到了

MyList.java:9: error: bad operand types for binary operator '%' if (iter.next() % 2 == 1) MyList.java:9:错误:二元运算符'%'的错误操作数类型if(iter.next()%2 == 1)

first type: Integer 第一种:整数

second type: int 第二种类型:int

If I change iter.next() to iter.next().intValue() , I get 如果我将iter.next()更改为iter.next().intValue() ,我得到

MyList.java:9: error: cannot find symbol if (iter.next().intValue() % 2 == 1) MyList.java:9:错误:找不到符号if(iter.next()。intValue()%2 == 1)

symbol: method intValue() 符号:方法intValue()

location: class Object location:类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. 您正在声明一个类型变量Integer ,它会影响java.lang.Integer类型。

Anywhere within the type body where you refer to Integer , you are referring to the type variable rather than the java.lang.Integer type. 在您引用Integer的类型主体中的任何位置,您指的是类型变量而不是java.lang.Integer类型。

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. 因此,您不能将它们与类型变量类型的操作数一起使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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