Java Program to Implement HashSet API

This Java program is to Implement HashSet Collection API. This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element.
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.

Here is the source code of the Java program to Implement HashSet Collection API. The Java program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. import java.util.Collection;
  2. import java.util.HashSet;
  3. import java.util.Iterator;
  4. import java.util.Set;
  5.  
  6. public class HashSetImpl<E>
  7. {
  8.     private Set<E> hashSet;
  9.  
  10.     /*
  11.      * Constructs a new, empty set; the backing HashMap instance has default
  12.      * initial capacity (16) and load factor (0.75).
  13.      */
  14.     public HashSetImpl()
  15.     {
  16.         hashSet = new HashSet<E>();
  17.     }
  18.  
  19.     /* Constructs a new set containing the elements in the specified collection. */
  20.     public HashSetImpl(Collection<? extends E> c)
  21.     {
  22.         hashSet = new HashSet<E>(c);
  23.     }
  24.  
  25.     /*
  26.      * constructs a new, empty set; the backing HashMap instance has the
  27.      * specified initial capacity and the specified load factor.
  28.      */
  29.     public HashSetImpl(int initialCapacity, float loadFactor)
  30.     {
  31.         hashSet = new HashSet<E>(initialCapacity, loadFactor);
  32.     }
  33.  
  34.     /*
  35.      * Constructs a new, empty set; the backing HashMap instance has the
  36.      * specified initial capacity and default load factor (0.75).
  37.      */
  38.     public HashSetImpl(int initialCapacity)
  39.     {
  40.         hashSet = new HashSet<E>(initialCapacity);
  41.     }
  42.  
  43.     /* adds the specified element if not already present */
  44.     public boolean add(E eobj)
  45.     {
  46.         return hashSet.add(eobj);
  47.     }
  48.  
  49.     /* return true if this set contains the specified element */
  50.     public boolean contains(Object obj)
  51.     {
  52.         return hashSet.contains(obj);
  53.     }
  54.  
  55.     /* returns true if the set is empty */
  56.     public boolean isEmpty()
  57.     {
  58.         return hashSet.isEmpty();
  59.     }
  60.  
  61.     /* returns an iterator over the elements in the set */
  62.     public Iterator<E> iterator()
  63.     {
  64.         return hashSet.iterator();
  65.     }
  66.  
  67.     /* removes the specified element from this set if present */
  68.     public boolean remove(Object obj)
  69.     {
  70.         return hashSet.remove(obj);
  71.     }
  72.  
  73.     /* returns the number of elements in set */
  74.     public int size()
  75.     {
  76.         return hashSet.size();
  77.     }
  78.  
  79.     /* removes all elements from this set */
  80.     public void clear()
  81.     {
  82.         hashSet.clear();
  83.     }
  84.  
  85.     /* Returns an array containing all of the elements in this set. */
  86.     public Object[] toArray()
  87.     {
  88.         return hashSet.toArray();
  89.     }
  90.  
  91.     /*
  92.      * Adds all of the elements in the specified collection to this set if
  93.      * they're not already present
  94.      */
  95.     public boolean addAll(Collection<? extends E> c)  
  96.       throws UnsupportedOperationException, ClassCastException,NullPointerException,IllegalArgumentException      
  97.     {
  98.         return hashSet.addAll(c);
  99.     }
  100.  
  101.     /*
  102.      * Retains only the elements in this set that are contained in the specified
  103.      * collection
  104.      */
  105.     public boolean retainAll(Collection<?> c)
  106.       throws UnsupportedOperationException, ClassCastException,NullPointerException
  107.     {
  108.         return hashSet.retainAll(c);
  109.     }
  110.  
  111.     /*
  112.      * Removes from this set all of its elements that are contained in the
  113.      * specified collection
  114.      */
  115.     public boolean removeAll(Collection<?> c)
  116.       throws UnsupportedOperationException, NullPointerException,ClassCastException
  117.     {
  118.         return hashSet.retainAll(c);
  119.     }
  120.  
  121.     /*
  122.      * Returns an array containing all of the elements in this set; the runtime
  123.      * type of the returned array is that of the specified array
  124.      */
  125.     public <T> T[] toArray(T[] a)
  126.       throws ArrayStoreException,NullPointerException
  127.     {
  128.         return hashSet.toArray(a);
  129.     }
  130.  
  131.     public static void main(String... arg)
  132.     {
  133.         HashSet<Integer> hashSet = new HashSet<Integer>();
  134.         if (hashSet.add(10))
  135.             System.out.println("element 10 added");
  136.         if (hashSet.add(20))
  137.             System.out.println("element 20 added");
  138.         if (hashSet.add(30))
  139.             System.out.println("element 30 added");
  140.  
  141.         System.out.println("the size of set is " + hashSet.size());
  142.  
  143.         if (hashSet.contains(40))
  144.             System.out.println("set contains 40");
  145.         else
  146.             System.out.println("set does not contain 40");
  147.  
  148.         if (hashSet.remove(20))
  149.             System.out.println("element 20 removed");
  150.         else
  151.             System.out.println("element 20 not removed");
  152.  
  153.         System.out.println("the element of set are");
  154.         Iterator<Integer> iterator = hashSet.iterator();
  155.         while (iterator.hasNext())
  156.         {
  157.             System.out.print(iterator.next() + "\t");
  158.         }
  159.         System.out.println();
  160.  
  161.         Set<Integer> removedSet = new HashSet<Integer>();
  162.         removedSet.add(10);
  163.         removedSet.add(20);
  164.  
  165.         System.out.println("the elements after removing");
  166.         hashSet.removeAll(removedSet);
  167.         Iterator<Integer> riterator = hashSet.iterator();
  168.         while(riterator.hasNext())
  169.         {
  170.             System.out.print(riterator.next() + "\t");
  171.         }
  172.         System.out.println();
  173.  
  174.         hashSet.clear();
  175.         System.out.println("hashSet cleared");
  176.         if (hashSet.isEmpty())
  177.             System.out.println("hashSet is empty");
  178.         else
  179.             System.out.println("hashSet is not empty");
  180.     }
  181. }


$javac HashSetImpl.java
$java HashSetImpl
 
element 10 added
element 20 added
element 30 added
the size of set is 3
set does not contain 40
element 20 removed
the element of set are
10	30	
the elements after removing
30	
hashSet cleared
hashSet is empty

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

advertisement
advertisement
If you wish to look at all Java Programming examples, go to Java Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.