I am using HashSets in an implementation to have fast adding, removing and element testing (amortized constant time).
However, I’d also like a method to obtain an arbitraty element from that set. The only way I am aware of is
Object arbitraryElement = set.iterator.next();
My question is – how fast (asymptotically speaking) is this? Does this work in (not amortized) constant time in the size of the set, or does the iterator().next() method do some operations that are slower? I ask because I seem to lose a log-factor in my implementation as experiments show, and this is one of the few lines affected.
Thank you very much!
HashSet.iterator().next()linearly scans the table to find the next contained item.For the default load factor of .75, you would have three full slots for every empty one.
There is, of course, no guarantee what the distribution of the objects in the backing array will be & the set will never actually be that full so scans will take longer.
I think you’d get amortized constant time.
Edit: The iterator does not create a deep copy of anything in the set. It only references the array in the
HashSet. Your example creates a few objects, but nothing more & no big copies.