Search code examples
javanulliteratoranonymous-class

How to check if Iterator.next() is == null?


How do I check if the next element in the list is null ?

while(it.hasNext()){

            System.out.println(it.next()+"\n");
        }

this is how I tried, but when the last element is null it prints it as null.

I tried to change it

 while(it.hasNext()){
    if(it.next()==null){
    }else             
        System.out.println(it.next()+"\n");
            }

but this just makes it worst because some of the elements don't even print!

This is my Iteration method/anonymous class

public Iterator<Filmi> iterator3DFilms ()throws FilmiException{
        if(filmList.isEmpty())
            throw new FilmiException("No Films on the list");
        return new Iterator<Filmi>(){
            private int index=0;
            public boolean hasNext(){
                return index <filmList.size();
            }
            public Filmi next(){
                Filmi lb = filmList.get(index++);

                if(lb.is3D()== true)
                    return lb;
                if(hasNext())
                    return next();
                return null;
            }
            public void remove(){}
        };
    }

The null print only happens at the last element Thank you.


Solution

  • Naturally, code like

    if (it.next() == null){
    } else {
        System.out.println(it.next()+"\n");
    }
    

    will consume every other non-null element, as you are observing. Plus calling it.next() without checking it.hasNext() is a recipe for disaster.

    Why not write

    Foo/*ToDo - use the correct type here*/ foo = it.next()
    if (foo != null){
        /*ToDo*/
    }
    

    instead?