HashSet Tutorial add remove equals contains hashCode


Two programs are given on HashSet Tutorial with different functionality.
  1. HashSet General: In this program, the general methods like contains(), equals(), add(), size(), remove(), toArray() and hashCode() usage is illustrated. Elements are printed with foreach loop.
  2. HashSet Operations: Iterator for printing the elements of HashSet is used. Methods like addAll, clear, retainAll, containsAll and toString are used. Two generics hash sets are created.

It is the first of the above two on HashSet Tutorial.

Note: It advised to get acquainted with the methods of HashSet, constructors and the super classes before going through this program. A complete tutorial is available at HashSet Tutorial.

Example on HashSet Tutorial
import java.util.*;
public class HashSetGeneral
{
  public static void main(String args[])
  {
    HashSet hs1 = new HashSet();
    hs1.add(10);
    hs1.add(10.5);
    hs1.add("hello");
    hs1.add("world");
    hs1.add(new StringBuffer("way2java"));
    hs1.add('A');
    System.out.println("hs1 elements: " + hs1);
    System.out.println("Contains element world: " + hs1.contains("world"));

		                       // ELEMENTS REMOVAL    
    System.out.println("\nNo. of elements before remove(): " + hs1.size());
    System.out.println("Removal status: " + hs1.remove("world"));
    System.out.println("No. of elements after remove(): " + hs1.size());

		                       // USING HASHCODE	
    HashSet hs2 = new HashSet();
    hs2.add(10);
    hs2.add(10.5);

    HashSet hs3 = new HashSet();
    hs3.add(10);
    hs3.add(10.5);

    int hc1 = hs2.hashCode();
    int hc2 = hs3.hashCode();
    System.out.println("\nHash code of hs2: " + hc1);
    System.out.println("Hash code of hs3: " + hc2);
    if(hs2.equals(hs3))
    {
      System.out.println("hs2 and hs3 contain same elements\n");
    }   
     	                     // USING TOARRAY
    Object obj[] = hs1.toArray();
    System.out.print("Array elements: ");
    for(Object o1 : obj)
    {
      System.out.print(o1 + " ");
    }
  }
}

Following explains all the methods used in the above code.

       HashSet hs1 = new HashSet();
       hs1.add(10);

A non-generics HashSet object hs1 is created and elements are added with add() method, inherited from Collection interface, the root interface of all collections classes.

       System.out.println("Contains element world: " + hs1.contains("world"));

The contains() method returns true if the element passed as parameter exists or false. The above statement returns true as "world" exists in the code. This method can be checked for existence of an element and can be used as follows in coding.

       if(! hs1.contains("world"))
       {
         hs1.add("world");
       }
       System.out.println("\nNo. of elements before remove(): " + hs1.size());
       System.out.println("Removal status: " + hs1.remove("world"));

The size() method returns the number of elements present in the hash set. The remove() method is used to remove an element. In the above statement element "world" is removed and when removed, the size falls by 1. Observe the screenshot.

       HashSet hs2 = new HashSet();
       HashSet hs3 = new HashSet();

Two HashSet objects hs2 and hs3 are created with the same elements of 10 and 10.5.

       int hc1 = hs2.hashCode();
       int hc2 = hs3.hashCode();

When their elements are same, their hash codes are same. Hash code is an integer number, an internal representation of an object how it is stored.

       if(hs2.equals(hs3))
       {
         System.out.println("hs2 and hs3 contain same elements\n");
       }

When their hash codes are same, the above equals() can be modified as follows.

       if(hs2 == hs3)
       {
         System.out.println("hs2 and hs3 contain same elements\n");
       }

With hash codes, two hash sets can be checked whether they contain the same elements or not.

       Object obj[] = hs1.toArray();
       for(Object o1 : obj)
       {
         System.out.print(o1 + " ");
       }

With toArray() method, inherited from Collection interface, any data structure can be converted into an array. toArray() method returns an array of Object class. Enhanced for loop, introduced with JDK 1.5, is used to iterate and print the elements.

       String str[] = (String[]) hs1.toArray();

If the coding requires a string array, in place of object array, the previous statement can be modified as above.

About Hashing and Hashcode

Comparing two strings letter by letter in a for loop is a time taking process. To make faster, the JVM converts each string into an integer number called hashcode. Different strings with different sequence of characters have different hashcodes. Comparison with integer numbers gives maximum performance. Usage of hashcode numbers for comparison, searching of duplicate elements and identification is faster.

Hashing is process of converting a string or object into a 32-bit hashcode integer number. Two objects are said to be equal if their hashcodes are same. hashCode() is used in combination with equals() method. When compared, hashing is done automatically by the JVM. Hashing, in data structures, is done implicitly in the basic operations with add(), contains(), remove() and size() etc. Hashing is more useful to compare the sets of large content.

Pass your comments on this HashSet Tutorial.

4 thoughts on “HashSet Tutorial add remove equals contains hashCode”

  1. sir , i m a bit confused , problem is whenever we create an object JVM allocates it a different memory location , now
    HashSet hs2 = new HashSet();
    HashSet hs3 = new HashSet();
    hs2 and hs3 must be having different memory location then how their hashcodes are same ?

Leave a Comment

Your email address will not be published.