简体   繁体   中英

ArrayList Iterator fails to iterate

My iterator which I've written, doesnt iterate as planned. It should iterate over an ArrayList but it keep looping over the first item: aylmao

Goal is to have a working custom iterator which will iterate a generic ArrayList

I'd very much rather ask this in the chat but no one is there atm.

Heres the trouble causing code:


    @Override
public Iterator<T> iterator() {
    final SimpleList<T> list = this;

    return new Iterator<T>() {

        int index = 0;

        @Override
        public boolean hasNext() {
            return index < list.size() && list.get(index) != null;
        }

        @Override
        public T next() {
            T temp = list.get(index++);
            index++;
            return temp;
        }

        public void remove() {
            throw new UnsupportedOperationException();
        }
    };

}

public static void main(String[] args) {
    SimpleList<String> list = new SimpleList<String>();
    list.append("aylmao");
    list.append("1aylmao");
    list.append("2aylmao");
    list.append("3aylmao");
    list.append("4aylmao");
    list.append("5aylmao");
    list.append("6aylmao");

    while (list.iterator().hasNext()) {

        System.out.println(list.iterator().next());
    }
}

Calling list.iterator() creates a new iterator every time.

Iterator<String> iter = list.iterator() will solve your problem

Just re-use iter.

For example:

SimpleList<String> list = new SimpleList<String>();
    list.append("aylmao");
    list.append("1aylmao");
    list.append("2aylmao");
    list.append("3aylmao");
    list.append("4aylmao");
    list.append("5aylmao");
    list.append("6aylmao");
    Iterator<String> iter = list.iterator()
    while (iter.hasNext()) {

        System.out.println(iter.next());
    }

Assign the iterator to the variable then add it to while-loop. list.iterator(); creates a new Iterator everytime.

Iterator iter = list.iterator();
while(iter.hasNext())
{
   System.out.println(iter.next());
}

Use :

for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) 
{
   System.out.println(iterator.next());
}

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