Hashset in Java

Posted on Updated on

HashSet extends AbstractSet and implements the Set interface. It does not define any additional methods beyond those provided by its superclasses and interfaces. Following are the features of HashSet class.

  1. It uses hash table internally for storage.
  2. As it implements Set interface, doesn’t allow duplicate entries.
  3. Insertion order of elements are not maintained.

Hashset provides following constructors.

Construtors Description
HashSet()  Default construtor
HashSet(Collection c)  Creates object of HashSet using elements of collection c.
HashSet(int capacity) Creates object of HashSet with initial capacity.
HashSet(int capacity, float fillRatio) Creates object of HashSet with initial capacity and fillRatio. The fill ratio must be between 0.0 and 1.0.

Load Factor/Fill Ratio

Load Factor determines how full the HashSet can be before it is resized upward. when the number of elements is greater than the capacity of the HashSet multiplied by its load factor/fill ratio, the HashSet is expanded. Default value of load factor is 0.75.

Example of HashSet

In Above Example we have created one hashSet which can hold any object. We have inserted Strings “obj1”, “obj2”, “obj3” and one int 4.

Output

[obj3, 4, obj1, obj2]

You can see in output that the insertion order of elements are not maintained in HashSet.

Example of Hash Set with Generics

we have created one hashSet which will hold only String.

Output

[String 4, String 3, String 2, String 1]

Example to add duplicate element in Hash Set.

Output

Add obj1 : true
Add obj2 : true
Add obj3 : true
Add obj3 : false
[obj3, obj1, obj2]

When we tried to add “obj3” second time, add method returned us false means this element is not added in the Hash Set.

Leave a Reply

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

Time limit is exhausted. Please reload CAPTCHA.