HashSet Collection Framework

text zoom

HashTable, HashMap and HashSet are the Collection classes in java.util package that make use of hashing algorithm to store objects. HashSet is a collection set that neither allows duplicate elements nor order or position its elements.

Let's take an example:










package visualbuilder;

import java.util.*;

public class ExampleHashSet

{

    public static void main(String arg[])

    {

        System.out.println( "Example of HashSet Class\n" );

        int size;

        HashSet <String>collection = new HashSet <String>();

        String str1 = "Java", str2 = "DB2", str3 = "Oracle", str4 = "J2EE"; 

        Iterator iterator;

        collection.add(str1);   

        collection.add(str2);  

        collection.add(str3);  

        collection.add(str4);

        System.out.println("Collection data: "); 

        iterator = collection.iterator();    

        while (iterator.hasNext())

        {

            System.out.print(iterator.next() + " "); 

        }

        System.out.println();

    // Get size of a collection

        size = collection.size();

        if (collection.isEmpty())

        {

            System.out.println("Collection is empty");

        }

        else

        {

            System.out.println( "Collection size: " + size);

        }

        System.out.println();

    // Remove specific data     

        collection.remove(str2);

        System.out.println("After removing [" + str2 + "]\n");

        System.out.print("Now collection data: ");

        iterator = collection.iterator();    

        while (iterator.hasNext())

        {

            System.out.print(iterator.next() + " "); 

        }

        System.out.println();

        size = collection.size();

        System.out.println("Collection size: " + size + "\n");

    //Collection empty

        collection.clear();

        size = collection.size();

        if (collection.isEmpty())

        {

            System.out.println("Collection is empty");

        }

        else

        {

            System.out.println( "Collection size: " + size);

        }

    }

}




 



Output:












In the following code keys are used to put and get values. To insert an element in the HashSet collection add() method is used. The size() method helps you in getting the size of the collection. If you want to delete any element, use the remove() method which takes index as parameter. When the HashSet is empty, our program checks for it and displays a message "Collection is empty". If the collection is not empty then program displays the size of HashSet.


 


 

                    

Copyright © 2010 VisualBuilder. All rights reserved