user3178137
user3178137

Reputation: 963

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?

Upvotes: 2

Views: 2961

Answers (3)

Ankur Shanbhag
Ankur Shanbhag

Reputation: 7804

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.

Upvotes: 4

Daniel Williams
Daniel Williams

Reputation: 8885

See this:

http://docs.oracle.com/javase/tutorial/collections/interfaces/collection.html

Iterators break if you modify the collection externally after getting the iterator

Upvotes: 0

aliteralmind
aliteralmind

Reputation: 20163

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.

Upvotes: 3

Related Questions