Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What the iteration cost on a HashSet also depend on the capacity of backing map?

From the JavaDocs of HashSet:

This class offers constant time performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets. Iterating over this set requires time proportional to the sum of the HashSet instance's size (the number of elements) plus the "capacity" of the backing HashMap instance (the number of buckets). Thus, it's very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important

Why does iteration takes time proportional to the sum(number of elements in set+ capacity of backing map) and not only to the number of elements in the set itself ?

.

like image 219
Geek Avatar asked Aug 22 '12 09:08

Geek


People also ask

What is default capacity and load factor of HashSet?

Constructs a new, empty set; the backing HashMap instance has default initial capacity (16) and load factor (0.75).

Can you iterate through a HashSet?

There are three simple ways to iterate over a HashSet, which is the following : Using Iterator. Without using Iterator (using for loop) Using for-each loop.

Why is HashSet backed by HashMap?

Hashset internally uses Hashmap for its implementation. HashMap Stores elements in form of key-value pair i.e each element has its corresponding key which is required for its retrieval during iteration. HashSet stores only objects no such key value pairs maintained.

What are the initial capacity and load factor of HashSet choose at least one correct answer?

Default initial capacity of the HashMap takes is 16 and load factor is 0.75f (i.e 75% of current map size).


1 Answers

HashSet is imlemented using a HashMap where the elements are the map keys. Since a map has a defined number of buckets that can contain one or more elements, iteration needs to check each bucket, whether it contains elements or not.

like image 93
Thomas Avatar answered Oct 26 '22 20:10

Thomas