0

I just can not figure out what's going on with this for loop. It assigns a User variable on every loop. But after the first loop, reader.read() is not called anymore (I debugged it), and user is always user1

Any clues?

public class Application {

    public static void main(String[] args) {
        UserReader reader = new UserReader();
        for( User user = reader.read(); user != null; ){
           System.out.println(user); // always "user1" 
        }
   }
}

public class UserReader {

    private Iterator<User> users;

    public ItemReaderImpl() {
        this.users = mock().iterator();
    }

    public User read() {
         return users.hasNext() ?
              users.next() : null;
    }

    private static List<User> mock() {
         List<User> users = new LinkedList<User>();
         users.add(new User("user1"));
         users.add(new User("user2"));
         users.add(new User("user3"));
         users.add(new User("user4"));
         users.add(new User("user5"));
         return users;
    }
}

Output

BOOM BOOM BOOM BOOM BOOM BOOM BOOM BOOM BOOM BOOM BOOM to infinity

Robert Estivill
  • 12,369
  • 8
  • 43
  • 64

0 Answers0