【问题标题】:java compiler error with generics and an iterator泛型和迭代器的java编译器错误
【发布时间】:2014-05-16 03:50:19
【问题描述】:

我有以下代码(是的,我知道迭代器的实现不正确。这是我正在写的考试题):

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 装箱为模运算,我得到 ​​p>

MyList.java:9:错误:二元运算符“%”的操作数类型错误 if (iter.next() % 2 == 1)

第一种类型:整数

第二种类型:int

如果我将iter.next() 更改为iter.next().intValue(),我会得到

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

符号:方法 intValue()

位置:类对象

但是,如果我改变了

 public class MyList<Integer>...

 public class MyList

然后错误消失。

想到发生了什么?

谢谢。

【问题讨论】:

    标签: java iterator


    【解决方案1】:

    这里,

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

    您正在声明一个类型变量 Integer,它隐藏了 java.lang.Integer 类型。

    在类型主体中引用Integer 的任何地方,您指的是类型变量而不是java.lang.Integer 类型。

    各种数值运算符不适用于随机类型(这是您的类型变量),它们仅适用于原始数值类型及其包装类。因此,您不能将它们与类型变量类型的操作数一起使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-30
      • 1970-01-01
      相关资源
      最近更新 更多