Wednesday, April 10, 2013

Java HashSet Example

Java HashSet Example

HashSet is the class, which is available in java.util package.  HashSet implements the set interface.

HashSet does not preservs the order, suppose if we inert the elments in the HashSet in some order, while
 Iterating we can not guarantee to get the same order.

HashSet allows the null values.

HashSet has the methods like add,remove,size,isEmpty...etc.

Java HashSet Sample Code : 

 

import java.util.Iterator;
import java.util.HashSet;

//HashSet Example Java
public class JavaHashSetExample {

    public static void main(String[] args) {
        // The advantage of HashSet is it sorts the elements.
        HashSet<String> hashSet = new HashSet<String>();
        hashSet.add("spring");
        hashSet.add("hibernate");
        hashSet.add("struts");
        hashSet.add(null);
        hashSet.add("webservices");
        System.out.println("size : " + hashSet.size());
        Iterator<String> iterator = hashSet.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
        hashSet.remove("struts");
        System.out.println("After removing struts");
        // after removing jsp
        iterator = hashSet.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
        if (hashSet.contains("struts")) {
            System.out.println("struts available");
        } else {
            System.out.println("struts not available");
        }

    }

}



Output of the code :

size : 5

null
webservices
hibernate
spring
struts

After removing struts

null
webservices
hibernate
spring
struts not available


2 comments :

 
Disclaimer : If you find any mistakes / corrections / feedback Please let us know...This website author shall not accept liability or responsibility for any errors, mistakes or misstatements found in this website.