原始类型的 Java 迭代器

标签 java iterator primitive private-members autoboxing

我有一个如下形式的 Java 类:

class Example {

  private byte[][] data;

  public Example(int s) { data = new byte[s][s]; }

  public byte getter(int x, int y)         { return byte[x][y]; }
  public void setter(int x, int y, byte z) { byte[x][y] = z;    }
}

我希望能够像这样使用迭代器在外部迭代私有(private)数据:

for(byte b : Example) { ;/* 做一些事情 */}

我试图实现一个私有(private)迭代器类,但我遇到了问题:

private class ExampleIterator implements Iterator {
  private int curr_x;
  private int curr_y;

  public ExampleIterator() { curr_x=0; curr_y=-1; }
  public boolean hasNext() { 
    return curr_x != field.length-1
        && curr_y != field.length-1; //is not the last cell?
  }
  public byte next() { // <-- Error is here: 
                       // Wants to change return type to Object
                       // Won't compile!
    if(curr_y=field.length) { ++curr_x; curr_y=0; }
    return field[curr_x][curr_y];
  }
  public void remove() { ; } //does nothing
}

我如何为基本类型(不是泛型)实现一个外部迭代器?这在 Java 中可行吗?

最佳答案

迭代器不能产生原始类型的值。但是,它可能会产生包装器类型的值 Byte .这些值可以是 auto-unboxed放入 byte(只要它们不是 null)。

private class ExampleIterator implements Iterator<Byte> {
  public boolean hasNext() { ... }
  public Byte next() { ... }
}

然后你可以像这样使用它:

for (byte b : example) { ... }

关于原始类型的 Java 迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15791210/

相关文章:

java - 如何验证用户在java中输入的数据

C# - 将 2 个列表与自定义元素进行比较

cryptography - 生成器 G 要求是 Diffie Hellman 算法中的原始根模 p

Java:在没有对象实例化的情况下将文本解析为原始数字

JavaScript 错误 : Cannot Convert Object to Primitive Value

java - 在 JavaFX 2 中将工具栏按钮设置为方形且大小相同

java - 为 java 项目创建 .exe

c++ - 使用迭代器访问成员字符串时出错::空

java - 验证 Java MessageFormat 字符串

c# - 使用迭代器编写自定义 IEnumerator<T>