Set :

  • Set is a child interface of Collection.
  • If we want to represent a group of individual object as a single entity where duplicates are not allowed and insertion order is not preserved, then we should go to the collection Set.
  • Set interface does not contain any new method, so we have to use only Collection interface methods.

HashSet

  • It is an implementation class of Set interface.
  • Underlying data structure is HashTable.
  • Duplicates are not allowed. If we are trying to insert duplicates, we will not get any compile-time error or run time error. Simply the add() method returns a boolean value that is false.
  • Insertion order is not preserved and all objects will be inserted based on hash code of objects.
  • Heterogeneous objects are allowed.
  • Null insertion is possible.
  • Implements Serializable and Clonable interface.
  • Not implements RandomAccess interface.
  • If our frequent operation is the searching operation, then HashSet is the best choice as Collection with the help of hash code of objects.

Constructors

  • Creates an empty HashSet with default initial capacity 16 and the fill ratio / load factor is 0.75(75%).

    HashSet h=new HashSet();

  • Create an empty HashSet by taking given initial capacity. Here load factor is also 0.75.

    HashSet h=new HashSet(int initial capacity);

  • Create an empty HashSet by taking given initial capacity and given load factor.

    HashSet h=new HashSet(int initial capacity, float load factor);

  • By taking any Collection object, we can create an equivalent HashSet object. Let's see a simple demo program on HashSet.

    Example

    HashSet h=new HashSet(Collection c);

Hash Set Demo.java:

  import java.util.*;
  class HashSetDemo
   {
     public static void main(String args[])
       {
         HashSet h=new HashSet();
         h.add("Gourav");
         h.add("Abhisek");
         h.add("Lagnika");
         h.add("Priti");
         h.add("Suman");
         h.add("Sonali");
         h.add(null);
         h.add(25);
         System.out.println(h.add("Gourav"));
         System.out.println(h);
       }
   }

Output

false
[null, Sonali, Lagnika, Priti, 25, Suman, Abhisek, Gourav]

Our Services:

Java Training | Python Training | Machine Learning with Python Training | Deep Learning with Python Training | Data Science with Python Training | Projects

SILAN Technology
Call to: 9439202111  |  9658317757  |  0674-2361252

Comment