[实现迭代器时的StackOverflowError

问题描述 投票:-1回答:1

我应该创建一个模拟,该模拟执行pythons xrange的工作,即在Java中选择一个起始编号,终止编号和步骤编号。我在将构造函数编号传递给Range类时遇到麻烦,因为它在线程“ main” java.lang.StackOverflowError中给了我一个异常。每次我执行程序时,Range构造函数都会变回“ Rane @ 365”,我不确定这是什么意思,但是我提供的数字消失了。

 package com.company;

 public class Main {

public static void main(String[] args) {

    for (Integer num: new Range(1,10,2)) {
        System.out.println(num++);
    }

}

}

这是我的Range类,它使用接口Iterator和接口Iterable

package com.company;

 import java.util.Iterator;

public class Range implements Iterable<Integer>, Iterator<Integer> {

public Range(int start, int stop, int step){

    start = start;
    stop = stop;
    step = step;
}


public Iterator<Integer> iterator() {

    return this;
}


public boolean hasNext() {
    if (!this.hasNext()) {
        return true;
    } else
    return false;
}


public Integer next() {
    if (!hasNext()) {
        throw new IllegalStateException("No next");
    }
    return null;
}

public void remove() {

}

}

我读过的东西使用了ArrayLists,而我在构造函数上没有发现任何东西,并且没有为Iterator和Iterable接口使用循环。我知道hasNext,next,remove是内置方法,循环在哪里?在Main类还是内置类之一中?

java recursion
1个回答
0
投票

这里有无限递归:

public boolean hasNext() {
    if (!this.hasNext()) {
      ...

此方法每次都会自我调用,从而增加堆栈,直到获得StackOverflowException。

© www.soinside.com 2019 - 2024. All rights reserved.