简体   繁体   中英

StackOverflowError when using Iterator to iterate through a list

I am trying to implement a toArray() method on a list. 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. 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. 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. When I click ArrayIndexList.java:158 it takes me to the return this.iterator() in my code. 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[] . Then you can wrap that with a List and return the iterator() of that. 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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM