Java HashSet Example

HashSet is a collection class. It extends AbstractSet class and implements Set interface. It is neither allow duplicate elements nor order of elements. HashSet does not guarantee that the order will remain constant over time. This class permits the null element also. HashSet uses internally hashing technique to store elements into HashSet.

Java Example:
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class HashSetExample {
 public static void main(String[] args) {

  Set hs = new HashSet();
  System.out.println("HashSet Initial Size:" 
    + hs.size());

  hs.add("Core Java");
  hs.add("Spring");
  hs.add("Hibernate");
  hs.add("JPA");
  hs.add("J2EE");
  hs.add("Spring"); // duplicate element
  hs.add("Struts");

  System.out.println("HashSet Elements:" + hs);
  System.out.println("HashSet Current Size:" 
    + hs.size());

  // Using Iterator
  Iterator itr = (Iterator) hs.iterator();
  System.out.println("HasSet Elements Using Iterator:");
  while (itr.hasNext()) {
   System.out.print(itr.next() + ", ");
  }

  // Using Enhanced for loop
  System.out.println("\nHasSet Elements Using forloop:");
  for (String str : hs) {
   System.out.print(str + ", ");
  }
 }
}
Output:
HashSet Initial Size:0
HashSet Elements:
[Struts, Hibernate, Core Java, J2EE, Spring, JPA]
HashSet Current Size:6
HasSet Elements Using Iterator:
Struts, Hibernate, Core Java, J2EE, Spring, JPA, 
HasSet Elements Using forloop:
Struts, Hibernate, Core Java, J2EE, Spring, JPA, 

Search: