HashSet Class in Java
HashSet Class
A HashSet represents a set of elements(objects). It does not guarantee the order of elements. Also it does not allow the duplicate elements to be stored.
Syntax for HashSet class as:
class HashSet <T>
Note: Here, <T> represents the generic type parameter. It represents which type of elements are being stored into the HashSet. Suppose, we want to create a HashSet to store a group of Strings, then we can create the object as:
HashSet<String> hs=new HashSet<String>();
HashSet Class constructors are as:
- HashSet();
- HashSet(int capacity);
- HashSet(int capacity,float loadfactor);
Here, capacity is used to initialize the capacity of the hash set to the given integer value capacity. The capacity grows automatically as elements are added to the HashSet.
Here,loadfactor determines the point where the capacity of HashSet would be increased internally.For example, the product of capacity and loadfactor
HashSet Class Methods:
Following are the methods of Java HashSet class are as follows:
S.No. | Modifier & Type | Method | Description |
---|---|---|---|
1) | boolean | add(obj) | This method adds an element obj to the HashSet. It returns true if the element is added to the HashSet, else it returns false. |
2) | boolean | remove(obj) | It is used to remove all of the elements from the HashSet, if it is present. It returns true if the element is removed successfully. |
3) | void | clear() | It is used to remove all of the elements from the HashSet. |
4) | boolean | contains(obj) | It is used to return true if the HashSet contains the specified element obj. |
5) | boolean | isEmpty() | It is used to return true if this set contains no elements. |
6) | int | size() | This returns the number of elements present in the HashSet. |
Java HashSet Example
import java.util.*; public class HashSetExample { public static void main(String[] args) { //Creating HashSet to store strings HashSet
hs=new HashSet (); //store some string elements hs.add("HTML"); hs.add("CSS"); hs.add("Java Script"); hs.add("Java"); //view the HashSet System.out.println("Hash set= "+hs); //add an iterator to hs. Iterator it=hs.iterator(); //display element by element using iterator System.out.println("Elements using iterator: "); while(it.hasNext()) { String s=(String)it.next(); System.out.println(s); //System.out.println(it.next()); }//end of while loop }//end of main }//end of class
Output:
Hash set= [Java, CSS, Java Script, HTML]Elements using iterator:
Java
CSS
Java Script
HTML