原始类型的Java迭代器

rec*_*nja 8 java primitive autoboxing iterator private-members

我有一个以下形式的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;    }
}
Run Code Online (Sandbox Code Playgroud)

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

for(byte b : Example) { ;/* do stuff */ }

我试图实现一个私有的Iterator类,但我遇到了问题:

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
}
Run Code Online (Sandbox Code Playgroud)

我如何为原始类型(非泛型)实现外部迭代器?这在Java中可行吗?

NPE*_*NPE 8

迭代器不能产生基本类型的值.但是,它可以产生包装类型的值Byte.这样的值可以自动拆箱byte(只要他们不是null).

private class ExampleIterator implements Iterator<Byte> {
  public boolean hasNext() { ... }
  public Byte next() { ... }
}
Run Code Online (Sandbox Code Playgroud)

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

for (byte b : example) { ... }
Run Code Online (Sandbox Code Playgroud)

  • 通常,像这样的自动装箱是一种快速生成大量垃圾的方法.但是,对于`Byte`,我相信大多数Java实现都使用flyweight模式(因为只有256个`byte`值),所以GC没有额外的负担.但是请注意,你必须使用`for(byte b:instanceOfExample)` - 你不能迭代一个类. (2认同)

Oro*_*102 6

Java 8引入了原始迭代器,允许您在int,long和double集合的迭代期间避免装箱/取消装箱.

您可以使用类型安全地实现泛型创建自己PrimitiveIterator的.也将实施.两者都非常简单.bytePrimitiveIterator<Byte,ByteConsumer>ByteConsumer

PrimitiveIterator.ofBytejdk 为什么没有?可能是因为机器字大小,通常不小于int.或者字节迭代器最好由流等完成.