Java HashSet
HashSet implements the set interface. It uses the hash table to make the collection to store different data types. The hash set is the unordered collection of different data types. In other words, we can say that the hash set doesn't maintain the order of insertion of the elements. The HashSet contains unique elements only. The duplicate elements inserted into the HashSet are considered only once in the collection. It can also contain null values. The indexing in the HashSet is done according to the Hash value of the element inserted into the HashSet. The default value of the initial position is 16, and the load factor is 0.75. Load factor and initial capacity are two factors which affect the performance of the Hash Table. Initial Capacity: It is the number of buckets in the Hash table. If the current size is full, then the number of buckets is automatically increasing. Load Factor: It decides when it increases the capacity of the Hash Map. Load Factor= Number of stored elements in the table/ Size of Hash Table. Time Complexity of Hash Set: HashSet uses the data structure is HashTable. The Average time complexity of HashSet for add(), remove(), contains() methods operation is O(1) time.
Internal working of HashSet:
The classes of the set interface are internally back up by Map. HashMap used to store the object internally in HashSet. When we enter the value in HashMap, then we need a key-value pair, but in HashSet, we need only value. Implementation:public transient HashMap map; public HashSet() { map=new HashMap (); // creating internally backing HashMap object. } public HashSet (int initialCapacity) { map= new HashMap (initialCapacity); // creating internally backing HashMap object. } private static final object PRESENT= new Object (); //Dummy value public boolean add (E e) { return map.put (e, PRESENT) ==null; //internally calls put () method of backing HashMap object to passing the elements. } public boolean remove (object o) { return map.put (o) == PRESENT; //internally call remove method of Map interface. }
Constructor
- HashSet (): It constructs the default HashSet.
- HashSet (Collection c): It initializes the HashSet using the elements of the collection.
- HashSet (int capacity): This initializes the capacity of the HashSet. The capacity of HashSet increased automatically when elements added in Hash set.
- HashSet (int capacity, float Loadfactor): This initializes the capacity of the HashSet and the load factor of the HashSet from its parameters. The load factor enters in float type and capacity at the given integer value type.
Methods
- add (Element e): It is used to add the specific element. If the element is present then returns false.
- clear (): It is used to remove all the elements of the set.
- contains (object o): It returns true when the elements found in the set.
- remove (object o): It is used to delete the element if element present in the set.
- iterator (): It is used to return the iterator in the set.
- isEmpty (): This method is used to check the set is empty or not.
- int size (): This method is used to return the size of the set.
- Object clone (): This method is used to create the same copy of the set.
- Using iterator: The iterator () method is to get an iterator over the element in the set. There is no particular order for returning the element.
import java.util.*; public class IterationDemo { public static void main (String[] args) { HashSet<String> h = new HashSet<String> (); h.add ("TutorialAndExample"); h.add ("for"); h.add ("Study purpose"); h.add ("Study purpose"); Iterator<String> i = h.iterator (); while (i.hasNext ()) System.out.println (i.next ()); } }Output:
TutorialAndExample for Study purpose
- Using for-each loop:
import java.util.*; public class IterationDemo { public static void main (String [] args) { HashSet<String> h = new HashSet<String> (); h.add ("TutorialAndExample"); h.add ("for"); h.add ("Study purpose"); h.add ("Study purpose"); for (String i: h) System.out.println (i); } }Output:
javatpoint for Study purpose
- Using forEach ():
import java.util.*; public class IterationDemo { public static void main (String [] args){ HashSet<String> h = new HashSet<String> (); h.add ("TutorialAndExample"); h.add ("TutorialAndExample"); h.add ("for"); h.add ("Study Purpose"); h.forEach (i -> System.out.println (i)); } }Output:
Study Purpose for TutorialAndExample
Difference between HashSet and TreeSet
HashSet | TreeSet |
1. Performance is faster. | 1. Performance is slower for most of the general operation, i.e., add, remove and search. |
2. There is no particular order for an element. | 2. Tree set provides the order for elements. |
3. For comparing, it uses the equals () method. | 3. For comparing, it uses the compareTo () method. |
4. The data structure for the hash set is HashTable. | 4. The Data Structure for TreeSet is Red-Black Tree. |
5. It allows only one null element. | 5. It doesn’t allow null element. |
6. Implemented using HashMap. | 6. Implemented using TreeMap. |
import java.io.*; import java.util. HashSet; public class AddDemo { public static void main (String args []) { HashSet<String> set = new HashSet<String> (); set.add ("Welcome"); set.add ("To"); set.add ("TutorialandExample"); System.out.println ("HashSet: " + set); } }Output:
HashSet: [Welcome, TutorialandExample, To]Example of clear () method:
import java.io.*; import java.util. HashSet; public class ClearDemo { public static void main (String args []) { HashSet<String> set = new HashSet<String> (); set.add ("Welcome"); set.add ("To"); set.add ("TutorialandExample"); System.out.println ("HashSet: " + set); set.clear (); System.out.println ("The final set: " + set); } }Output:
HashSet: [Welcome, TutorialandExample, To] The final set: []
contains () method
import java.io.*; import java.util. HashSet; public class ContainDemo { public static void main (String args []) { HashSet<String> set = new HashSet<String> (); set.add ("Welcome"); set.add ("To"); set.add ("TutorialandExample"); System.out.println ("HashSet: " + set); System.out.println ("Does the Set contain ‘TutorialandExample’?” + set.contains ("TutorialandExample")); System.out.println ("Does the Set contain ‘4’?” + set.contains ("4")); System.out.println ("Does the Set contains ‘and’?" + set.contains ("and")); } }Output:
HashSet: [TutorialandExample, Welcome, To] Does the Set contain 'TutorialandExample’? true Does the Set contain '4'? false Does the Set contains 'and'? falseremove () method
import java.io.*; import java.util. HashSet; public class ContainDemo { public static void main (String args []) { HashSet<String> set = new HashSet<String> (); set.add ("Welcome"); set.add ("To"); set.add ("TutorialandExample"); System.out.println ("HashSet: " + set); set.remove ("Welcome"); System.out.println ("HashSet after remove the elements: "+ set); } }Output:
HashSet: [TutorialandExample, Welcome, To] HashSet after remove the elements: [TutorialandExample, To]isEmpty () method:
import java.io.*; import java.util. HashSet; public class EmptyDemo { public static void main (String args []) { HashSet<String> set = new HashSet<String> (); set.add ("javatpoint"); set.add ("and"); set.add ("TutorialandExample"); System.out.println ("HashSet: " + set); System.out.println ("Is the set empty: " + set.isEmpty ()); set.clear (); System.out.println ("Is the set empty: " + set.isEmpty ()); } }Output:
HashSet: [TutorialandExample, Welcome, To] Is the set empty: false Is the set empty: truesize () method:
import java.io.*; import java.util. HashSet; public class SizeDemo { public static void main (String args []) { HashSet<String> set = new HashSet<String> (); set.add ("Welcome"); set.add ("To"); set.add ("TutorialandExample"); System.out.println ("HashSet: " + set); System.out.println ("The size of set is: " + set.size ()); } }Output:
HashSet: [TutorialandExample, Welcome, To] The size of set is: 3clone () method:
import java.io.*; import java.util. HashSet; public class CloneDemo { public static void main (String args []) { HashSet<String> set = new HashSet<String> (); set.add ("Welcome"); set.add ("To"); set.add ("TutorialandExample"); System.out.println ("HashSet: " + set); HashSet clone= new HashSet (); clone = (HashSet) set.clone (); System.out.println ("The new set: " + clone); } } Output: HashSet: [TutorialandExample, Welcome, To] The new set: [Welcome, To, TutorialandExample]iterator () method:
import java.io.*; import java.util.*; public class IteratorDemo { public static void main (String args []) { HashSet<String> set = new HashSet<String> (); set.add ("Welcome"); set.add ("To"); set.add ("TutorialandExample"); System.out.println ("HashSet: " + set); Iterator value = set.iterator (); System.out.println ("The iterator values are: "); while (value.hasNext ()) { System.out.println (value.next ()); } } }Output:
HashSet: [TutorialandExample, Welcome, To] The iterator values are: TutorialandExample Welcome To