[英]StackOverflowError when using Iterator to iterate through a list
I am trying to implement a toArray() method on a list.我正在尝试在列表上实现一个 toArray() 方法。 Initially I got an error saying I could only iterate over an array or an instance of java.lang.iterable when using the for each loop, so I did some research and tried using the Iterator.
最初我收到一个错误,说在使用 for each 循环时我只能迭代数组或 java.lang.iterable 的实例,所以我做了一些研究并尝试使用迭代器。 However, now it looks like it's stuck in something like a recursive loop (I think).
但是,现在看起来它陷入了递归循环之类的事情中(我认为)。 Here is the section of my code I'm having trouble with:
这是我遇到问题的代码部分:
public Object[] toArray(){
Object[] arr = new Object[this.size()]
int i = 0;
for(E e: this){
arr[i] = e;
i++;
}
return arr;
}
@Override
public Iterator<E> iterator() {
return this.iterator();
}
I've narrowed it down to how I've defined my public Iterator<E> iterator()
method since the program works ok if I use other values instead of this
in the foreach loop.我已经将范围缩小到如何定义我的
public Iterator<E> iterator()
方法,因为如果我在 foreach 循环中使用其他值而不是this
值,程序就可以正常工作。 The error I'm getting is Exception in thread "main"java.lang.StackOverflowError at arrayIndexList.ArrayIndexList.iterator(ArrayIndexList.java:158)
repeated exactly as it is over and over again, but not in an infinite loop since it terminates.我得到的错误是
Exception in thread "main"java.lang.StackOverflowError at arrayIndexList.ArrayIndexList.iterator(ArrayIndexList.java:158)
一再重复,但不是无限循环,因为它终止. When I click ArrayIndexList.java:158
it takes me to the return this.iterator()
in my code.当我单击
ArrayIndexList.java:158
它会带我return this.iterator()
代码中的return this.iterator()
。 What am I missing here?我在这里缺少什么?
First, you need to pass the Class<E>
to your constructor and save it so you can construct your array type properly in toArray()
- and return an E[]
.首先,您需要将
Class<E>
传递给您的构造函数并保存它,以便您可以在toArray()
正确构造您的数组类型 - 并返回一个E[]
。 Then you can wrap that with a List
and return the iterator()
of that.然后你可以用一个
List
包装它并返回它的iterator()
。 Like,喜欢,
private Class<E> cls; // <-- make sure you assign this in your constructor
public E[] toArray() {
E[] arr = Array.newInstance(cls, this.size()); // <-- here is how you get an E[]
int i = 0;
for (E e : this) {
arr[i] = e;
i++;
}
return arr;
}
@Override
public Iterator<E> iterator() {
return Arrays.asList(this.toArray()).iterator();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.