djaszak
djaszak

Reputation: 125

Why does an iterator given into mine constructor , doesn't add iterator.next() to my list?

I am implementing a new iterator. The constructor of this new iterator gets an iterator and my idea is that I want to add all entries of the iterable object, that the iterator is connected to but the iterator doesn't add the entries how it should. This is my code:

public PredicateIterator(Iterator<T> iter, Predicate<T> pred, T argument){
        List<T> buffList = new LinkedList<>();
        while(iter.hasNext()){
            buffList.add(iter.next());
        }
    }

When I debug it, it tells me that the size of bufflist is 0 and iter.next() is Test1, but more it doesn't do. Thanks for any help.

Upvotes: 2

Views: 49

Answers (1)

Eran
Eran

Reputation: 393841

Your buffList is a local variable of the constructor, which means it will be gone once the execution of the constructor is done (or, to be more exact, it will become eligible for garbage collection and you'll have no access to it).

Store the elements in an instance variable:

class PredicateIterator {
    private List<T> buffList;

    ...

    public PredicateIterator(Iterator<T> iter, Predicate<T> pred, T argument){
        this.buffList = new LinkedList<>();
        while(iter.hasNext()){
            buffList.add(iter.next());
        }
    }

    ...
}

Upvotes: 4

Related Questions