Home » Core Java » HashSet in Java

HashSet in Java

HashSet & its feature ::
1.  HashSet class is an important class of Collection framework.
2.  HashSet extends generic AbstractSet.
3.  HashSet implements generic Set, cloneable and java.io.Serializable interface.
4.  HashSet internally crates a HashMap with initial capacity 16 and load factor of 0.75.HashSet stores values in the key of the HashMap.So HashSet has always have unique elements stored.If you try to add duplicate element HashSet replaces the old value with new value.
5.  HashSet is unsynchronized i.e. it is not thread safe.But, it can be made synchronized explicitly like below

5.  HashSet can accept any element including multiple null values.
7.  HashSet uses Iterator interface to traverse the elements.While traversing the elements using iterator if the      structure of the HashSet is modified using add or remove method ,iterator will throw ConcurrentModificationException.So iterators for HashSet are fail-fast..While iterating you can add new elements without getting ConcurrentModificationException.
8. HashSet 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.

Sample Program ::

Output ::

Now let us see an example of ConcurrentModificationException.In the below program while iterating the HashSet,i am modifying the structure of the HashSet by adding a new element.So I am getting ConcurrentModificationException.
Example of ConcurrentModificationException ::

Output ::


Leave a comment

Your email address will not be published. Required fields are marked *

14 − eight =