Java—使用带数组的迭代器

Java—使用带数组的迭代器,java,arrays,iterator,Java,Arrays,Iterator,我不熟悉Java中的“迭代器”概念,需要在代码中实现它的帮助。代码如下: class IteratorExample { int tstArray []; IteratorExample(){ } public void addNum(int num){ tstArray[0] = num; //And yes, I can only add one number at the moment, but it is not what I

我不熟悉Java中的“迭代器”概念,需要在代码中实现它的帮助。代码如下:

class IteratorExample {

int tstArray [];

IteratorExample(){

}

public void addNum(int num){

   tstArray[0] = num; //And yes, I can only add one number at the moment, but it
                      is not what I want to focus on right now.
}


public Iterator<Integer> innerIterator(){
    return new methodIterator();
}

 class methodIterator implements Iterator<Integer> {
    public int index;
    private methodIterator(){
        index = 0;
    }

    public boolean hasNext(){
        return index < tstArray.length;

    }
    public Integer next(){
        return;
    }


  }    

public static void main(String[] args){
    IteratorExample sample = new IteratorExample();
  test(sample);
}

public static void test(IteratorExample arr){
 arr.addNum(1);
 system.out.print(arr);
}

}
类迭代器示例{
int tstArray[];
迭代器示例(){
}
公共void addNum(int num){
tstArray[0]=num;//是的,我现在只能添加一个数字,但是
这不是我现在想要关注的。
}
公共迭代器innerIterator(){
返回新的methodIterator();
}
类methodIterator实现迭代器{
公共整数指数;
私有methodIterator(){
指数=0;
}
公共布尔hasNext(){
返回指数

这是迄今为止编写的代码。我想使用addNum()方法将一个数字添加到数组中,然后使用system.print从main显示它(是的,我知道我需要一个toString方法来显示数字,而不是内存地址,这将在稍后实现,现在我只关注如何使其工作。)

要使
迭代器工作,可以使用
next()
方法

public Integer next(){
    return tstArray[index++];
}
如果索引太大,这会抛出一个
ArrayIndexOutOfBoundsException
,而
迭代器的规范则说明它应该抛出一个
NoTouchElementException
。为了做好这件事,你可以写

public Integer next(){
    if (index < tstArray.length)
        return tstArray[index++];
    throw new NoSuchElementException();
}
public Integer next(){
if(索引
您的实际问题是什么?“是的,我现在只能添加一个数字,但这不是我现在想要关注的。”-事实上,这是您应该关注的。”因为它包括迭代器所需的基础结构。为什么要尝试将迭代器添加到非集合类型?我正在尝试比较数组和arraylist与迭代器之间的运行速度。这是非常规的(我可以补充一点不实用吗?),但这是真正的原因。顺便说一句,你不能打印内存地址