简体   繁体   中英

Custom iterator won't print anything when trying to iterate through an ArrayList

I'm very new to iterators but for an assignment I wrote a custom Iterator and I want to simply print out object as I iterate through a list of them but it keeps printing nothing and I have no idea why.

Here's the custom iterator code:

import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;

public class MyList<T> implements Iterable<T> {
    private List<T> list;

    private class MyIterator<t> implements Iterator<t> {
        int lSize = list.size();
        int lPoint = 0;

        public boolean hasNext() {          
            return (lPoint < lSize);
        }

        public t next() {                   
            if (!hasNext()) {
                throw new NoSuchElementException();
            }

            t val = (t) list.get(lPoint);
            lPoint++;

            return val;
        }

    }

    public MyList(List<T> list) {
        this.list = list;
    }

    public Iterator<T> iterator() {
        return new MyIterator<>();
    }

}

Here's the class I'm using to test it:

Public class TestCloning {

    Electronics test = new Electronics("Test", 100, 10);
    Electronics test3 = new Electronics("Test2", 300, 30);
    List<Electronics> order1 = new ArrayList<>();
    MyList<Electronics> mList1 = new MyList<>(order1);
    Iterator<Electronics> mIterator1 = mList1.iterator();

    public void testIterator(){
        order1.add(test);
        order1.add(test3);
        while (mIterator1.hasNext()){
            System.out.println(mIterator1.next().toString());
        }
    }
}

This is mainly because the lSize=0 The reason why it is zero is because you add the list of things to myList before you actually add any items into that list.

List<String> order1 = new ArrayList<>();
order1.add(test);
order1.add(test3);
MyList<String> mList1 = new MyList<>(order1);
Iterator<String> mIterator1 = mList1.iterator();

If you flip the order, add things to the order list, then create your custom one everything will work as you'd expect.

Also, I suggest in the future, don't use any custom iterators or lists that wrap normal lists. I understand this is for the purpose of an assignment, and then acceptable

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