Q:

Java iterator hasNext() method allways false

We have a HashSet of objects:
private Set<Client> clients = new HashSet<Client>();
And iterator for it:
private Iterator<Client> iterator = clients.iterator();
Lets add object to that set and print out iterators hasNext method output:
Client client = new Client(name);
clients.add(client);
System.out.println(iterator.hasNext());
The output is: "false". Why?

A:

The iterator never changes once created--it only works on the elements that were in the set when you got it. It doesn't recognize that after you've created it, you added an element. Just re-get the iterator after all elements have been added.

A:

The Iterator for the HashSet class is a fail-fast iterator. From the documentation of the HashSet class:

The iterators returned by this class's iterator method are fail-fast:
  if the set is modified at any time after the iterator is created, in
  any way except through the iterator's own remove method, the Iterator
  throws a ConcurrentModificationException. Thus, in the face of
  concurrent modification, the iterator fails quickly and cleanly,
  rather than risking arbitrary, non-deterministic behavior at an
  undetermined time in the future.

Here is a nice detailed explanation of the Iterator internal implementation.

